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,
123 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
124 return fs.rootnode().Child(name, replace)
127 func (fs *collectionFileSystem) FS() FileSystem {
131 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
132 return fs.rootnode().FileInfo()
135 func (fs *collectionFileSystem) IsDir() bool {
139 func (fs *collectionFileSystem) Lock() {
143 func (fs *collectionFileSystem) Unlock() {
144 fs.rootnode().Unlock()
147 func (fs *collectionFileSystem) RLock() {
148 fs.rootnode().RLock()
151 func (fs *collectionFileSystem) RUnlock() {
152 fs.rootnode().RUnlock()
155 func (fs *collectionFileSystem) Parent() inode {
156 return fs.rootnode().Parent()
159 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
160 return 0, ptr, ErrInvalidOperation
163 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
164 return 0, ptr, ErrInvalidOperation
167 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
168 return fs.rootnode().Readdir()
171 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
172 fs.rootnode().SetParent(parent, name)
175 func (fs *collectionFileSystem) Truncate(int64) error {
176 return ErrInvalidOperation
179 func (fs *collectionFileSystem) Sync() error {
183 txt, err := fs.MarshalManifest(".")
185 return fmt.Errorf("sync failed: %s", err)
191 err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
192 "collection": map[string]string{
193 "manifest_text": coll.ManifestText,
195 "select": []string{"uuid"},
198 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
203 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
204 node, err := rlookup(fs.fileSystem.root, path)
208 dn, ok := node.(*dirnode)
210 return ErrNotADirectory
214 names := dn.sortedNames()
216 // Caller only wants to flush the specified dir,
217 // non-recursively. Drop subdirs from the list of
219 var filenames []string
220 for _, name := range names {
221 if _, ok := dn.inodes[name].(*filenode); ok {
222 filenames = append(filenames, name)
227 for _, name := range names {
228 child := dn.inodes[name]
232 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
235 func (fs *collectionFileSystem) memorySize() int64 {
236 fs.fileSystem.root.Lock()
237 defer fs.fileSystem.root.Unlock()
238 return fs.fileSystem.root.(*dirnode).memorySize()
241 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
242 fs.fileSystem.root.Lock()
243 defer fs.fileSystem.root.Unlock()
244 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
247 func (fs *collectionFileSystem) Size() int64 {
248 return fs.fileSystem.root.(*dirnode).TreeSize()
251 // filenodePtr is an offset into a file that is (usually) efficient to
252 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
254 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
255 // corresponds to file offset filenodePtr.off. Otherwise, it is
256 // necessary to reexamine len(filenode.segments[0]) etc. to find the
257 // correct segment and offset.
258 type filenodePtr struct {
265 // seek returns a ptr that is consistent with both startPtr.off and
266 // the current state of fn. The caller must already hold fn.RLock() or
269 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
274 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
276 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
277 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
280 // meaningless anyway
282 } else if ptr.off >= fn.fileinfo.size {
283 ptr.segmentIdx = len(fn.segments)
285 ptr.repacked = fn.repacked
287 } else if ptr.repacked == fn.repacked {
288 // segmentIdx and segmentOff accurately reflect
289 // ptr.off, but might have fallen off the end of a
291 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
298 ptr.repacked = fn.repacked
300 if ptr.off >= fn.fileinfo.size {
301 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
304 // Recompute segmentIdx and segmentOff. We have already
305 // established fn.fileinfo.size > ptr.off >= 0, so we don't
306 // have to deal with edge cases here.
308 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
309 // This would panic (index out of range) if
310 // fn.fileinfo.size were larger than
311 // sum(fn.segments[i].Len()) -- but that can't happen
312 // because we have ensured fn.fileinfo.size is always
314 segLen := int64(fn.segments[ptr.segmentIdx].Len())
315 if off+segLen > ptr.off {
316 ptr.segmentOff = int(ptr.off - off)
324 // filenode implements inode.
325 type filenode struct {
330 // number of times `segments` has changed in a
331 // way that might invalidate a filenodePtr
333 memsize int64 // bytes in memSegments
338 // caller must have lock
339 func (fn *filenode) appendSegment(e segment) {
340 fn.segments = append(fn.segments, e)
341 fn.fileinfo.size += int64(e.Len())
344 func (fn *filenode) SetParent(p inode, name string) {
348 fn.fileinfo.name = name
351 func (fn *filenode) Parent() inode {
357 func (fn *filenode) FS() FileSystem {
361 // Read reads file data from a single segment, starting at startPtr,
362 // into p. startPtr is assumed not to be up-to-date. Caller must have
364 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
365 ptr = fn.seek(startPtr)
367 err = ErrNegativeOffset
370 if ptr.segmentIdx >= len(fn.segments) {
374 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
378 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
381 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
389 func (fn *filenode) Size() int64 {
392 return fn.fileinfo.Size()
395 func (fn *filenode) FileInfo() os.FileInfo {
401 func (fn *filenode) Truncate(size int64) error {
404 return fn.truncate(size)
407 func (fn *filenode) truncate(size int64) error {
408 if size == fn.fileinfo.size {
412 if size < fn.fileinfo.size {
413 ptr := fn.seek(filenodePtr{off: size})
414 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
415 if seg, ok := fn.segments[i].(*memSegment); ok {
416 fn.memsize -= int64(seg.Len())
419 if ptr.segmentOff == 0 {
420 fn.segments = fn.segments[:ptr.segmentIdx]
422 fn.segments = fn.segments[:ptr.segmentIdx+1]
423 switch seg := fn.segments[ptr.segmentIdx].(type) {
425 seg.Truncate(ptr.segmentOff)
426 fn.memsize += int64(seg.Len())
428 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
431 fn.fileinfo.size = size
434 for size > fn.fileinfo.size {
435 grow := size - fn.fileinfo.size
438 if len(fn.segments) == 0 {
440 fn.segments = append(fn.segments, seg)
441 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
443 fn.segments = append(fn.segments, seg)
445 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
448 seg.Truncate(seg.Len() + int(grow))
449 fn.fileinfo.size += grow
455 // Write writes data from p to the file, starting at startPtr,
456 // extending the file size if necessary. Caller must have Lock.
457 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
458 if startPtr.off > fn.fileinfo.size {
459 if err = fn.truncate(startPtr.off); err != nil {
460 return 0, startPtr, err
463 ptr = fn.seek(startPtr)
465 err = ErrNegativeOffset
468 for len(p) > 0 && err == nil {
470 if len(cando) > maxBlockSize {
471 cando = cando[:maxBlockSize]
473 // Rearrange/grow fn.segments (and shrink cando if
474 // needed) such that cando can be copied to
475 // fn.segments[ptr.segmentIdx] at offset
477 cur := ptr.segmentIdx
478 prev := ptr.segmentIdx - 1
480 if cur < len(fn.segments) {
481 _, curWritable = fn.segments[cur].(*memSegment)
483 var prevAppendable bool
484 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
485 _, prevAppendable = fn.segments[prev].(*memSegment)
487 if ptr.segmentOff > 0 && !curWritable {
488 // Split a non-writable block.
489 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
490 // Truncate cur, and insert a new
493 fn.segments = append(fn.segments, nil)
494 copy(fn.segments[cur+1:], fn.segments[cur:])
496 // Split cur into two copies, truncate
497 // the one on the left, shift the one
498 // on the right, and insert a new
499 // segment between them.
500 fn.segments = append(fn.segments, nil, nil)
501 copy(fn.segments[cur+2:], fn.segments[cur:])
502 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
507 seg.Truncate(len(cando))
508 fn.memsize += int64(len(cando))
509 fn.segments[cur] = seg
510 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
515 } else if curWritable {
516 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
521 // Shrink cando if needed to fit in
523 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
524 cando = cando[:cangrow]
528 if cur == len(fn.segments) {
529 // ptr is at EOF, filesize is changing.
530 fn.fileinfo.size += int64(len(cando))
531 } else if el := fn.segments[cur].Len(); el <= len(cando) {
532 // cando is long enough that we won't
533 // need cur any more. shrink cando to
534 // be exactly as long as cur
535 // (otherwise we'd accidentally shift
536 // the effective position of all
537 // segments after cur).
539 copy(fn.segments[cur:], fn.segments[cur+1:])
540 fn.segments = fn.segments[:len(fn.segments)-1]
542 // shrink cur by the same #bytes we're growing prev
543 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
549 ptr.segmentOff = fn.segments[prev].Len()
550 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
551 fn.memsize += int64(len(cando))
555 // Insert a segment between prev and
556 // cur, and advance prev/cur.
557 fn.segments = append(fn.segments, nil)
558 if cur < len(fn.segments) {
559 copy(fn.segments[cur+1:], fn.segments[cur:])
563 // appending a new segment does
564 // not invalidate any ptrs
567 seg.Truncate(len(cando))
568 fn.memsize += int64(len(cando))
569 fn.segments[cur] = seg
573 // Finally we can copy bytes from cando to the current segment.
574 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
578 ptr.off += int64(len(cando))
579 ptr.segmentOff += len(cando)
580 if ptr.segmentOff >= maxBlockSize {
581 fn.pruneMemSegments()
583 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
588 fn.fileinfo.modTime = time.Now()
593 // Write some data out to disk to reduce memory use. Caller must have
595 func (fn *filenode) pruneMemSegments() {
596 // TODO: share code with (*dirnode)flush()
597 // TODO: pack/flush small blocks too, when fragmented
598 for idx, seg := range fn.segments {
599 seg, ok := seg.(*memSegment)
600 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
603 // Setting seg.flushing guarantees seg.buf will not be
604 // modified in place: WriteAt and Truncate will
605 // allocate a new buf instead, if necessary.
606 idx, buf := idx, seg.buf
607 done := make(chan struct{})
609 // If lots of background writes are already in
610 // progress, block here until one finishes, rather
611 // than pile up an unlimited number of buffered writes
612 // and network flush operations.
613 fn.fs.throttle().Acquire()
616 locator, _, err := fn.FS().PutB(buf)
617 fn.fs.throttle().Release()
620 if seg.flushing != done {
621 // A new seg.buf has been allocated.
625 // TODO: stall (or return errors from)
626 // subsequent writes until flushing
627 // starts to succeed.
630 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
631 // Segment has been dropped/moved/resized.
634 fn.memsize -= int64(len(buf))
635 fn.segments[idx] = storedSegment{
646 // Block until all pending pruneMemSegments/flush work is
647 // finished. Caller must NOT have lock.
648 func (fn *filenode) waitPrune() {
649 var pending []<-chan struct{}
651 for _, seg := range fn.segments {
652 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
653 pending = append(pending, seg.flushing)
657 for _, p := range pending {
662 type dirnode struct {
663 fs *collectionFileSystem
667 func (dn *dirnode) FS() FileSystem {
671 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
672 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
673 gn := &getternode{Getter: func() ([]byte, error) {
676 coll.ManifestText, err = dn.fs.MarshalManifest(".")
680 data, err := json.Marshal(&coll)
682 data = append(data, '\n')
686 gn.SetParent(dn, name)
689 return dn.treenode.Child(name, replace)
692 type fnSegmentRef struct {
697 // commitBlock concatenates the data from the given filenode segments
698 // (which must be *memSegments), writes the data out to Keep as a
699 // single block, and replaces the filenodes' *memSegments with
700 // storedSegments that reference the relevant portions of the new
703 // bufsize is the total data size in refs. It is used to preallocate
704 // the correct amount of memory when len(refs)>1.
706 // If sync is false, commitBlock returns right away, after starting a
707 // goroutine to do the writes, reacquire the filenodes' locks, and
708 // swap out the *memSegments. Some filenodes' segments might get
709 // modified/rearranged in the meantime, in which case commitBlock
710 // won't replace them.
712 // Caller must have write lock.
713 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
717 if err := ctx.Err(); err != nil {
720 done := make(chan struct{})
722 segs := make([]*memSegment, 0, len(refs))
723 offsets := make([]int, 0, len(refs)) // location of segment's data within block
724 for _, ref := range refs {
725 seg := ref.fn.segments[ref.idx].(*memSegment)
726 if !sync && seg.flushingUnfinished() {
727 // Let the other flushing goroutine finish. If
728 // it fails, we'll try again next time.
732 // In sync mode, we proceed regardless of
733 // whether another flush is in progress: It
734 // can't finish before we do, because we hold
735 // fn's lock until we finish our own writes.
737 offsets = append(offsets, len(block))
740 } else if block == nil {
741 block = append(make([]byte, 0, bufsize), seg.buf...)
743 block = append(block, seg.buf...)
745 segs = append(segs, seg)
747 blocksize := len(block)
748 dn.fs.throttle().Acquire()
749 errs := make(chan error, 1)
753 locator, _, err := dn.fs.PutB(block)
754 dn.fs.throttle().Release()
759 for idx, ref := range refs {
762 // In async mode, fn's lock was
763 // released while we were waiting for
764 // PutB(); lots of things might have
766 if len(ref.fn.segments) <= ref.idx {
767 // file segments have
768 // rearranged or changed in
772 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
773 // segment has been replaced
776 } else if seg.flushing != done {
777 // seg.buf has been replaced
782 data := ref.fn.segments[ref.idx].(*memSegment).buf
783 ref.fn.segments[ref.idx] = storedSegment{
787 offset: offsets[idx],
790 // atomic is needed here despite caller having
791 // lock: caller might be running concurrent
792 // commitBlock() goroutines using the same
793 // lock, writing different segments from the
795 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
807 type flushOpts struct {
812 // flush in-memory data and remote-cluster block references (for the
813 // children with the given names, which must be children of dn) to
814 // local-cluster persistent storage.
816 // Caller must have write lock on dn and the named children.
818 // If any children are dirs, they will be flushed recursively.
819 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
820 cg := newContextGroup(ctx)
823 goCommit := func(refs []fnSegmentRef, bufsize int) {
825 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
829 var pending []fnSegmentRef
830 var pendingLen int = 0
831 localLocator := map[string]string{}
832 for _, name := range names {
833 switch node := dn.inodes[name].(type) {
835 grandchildNames := node.sortedNames()
836 for _, grandchildName := range grandchildNames {
837 grandchild := node.inodes[grandchildName]
839 defer grandchild.Unlock()
841 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
843 for idx, seg := range node.segments {
844 switch seg := seg.(type) {
846 loc, ok := localLocator[seg.locator]
849 loc, err = dn.fs.LocalLocator(seg.locator)
853 localLocator[seg.locator] = loc
856 node.segments[idx] = seg
858 if seg.Len() > maxBlockSize/2 {
859 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
862 if pendingLen+seg.Len() > maxBlockSize {
863 goCommit(pending, pendingLen)
867 pending = append(pending, fnSegmentRef{node, idx})
868 pendingLen += seg.Len()
870 panic(fmt.Sprintf("can't sync segment type %T", seg))
875 if opts.shortBlocks {
876 goCommit(pending, pendingLen)
881 // caller must have write lock.
882 func (dn *dirnode) memorySize() (size int64) {
883 for _, name := range dn.sortedNames() {
884 node := dn.inodes[name]
887 switch node := node.(type) {
889 size += node.memorySize()
891 for _, seg := range node.segments {
892 switch seg := seg.(type) {
894 size += int64(seg.Len())
902 // caller must have write lock.
903 func (dn *dirnode) sortedNames() []string {
904 names := make([]string, 0, len(dn.inodes))
905 for name := range dn.inodes {
906 names = append(names, name)
912 // caller must have write lock.
913 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
914 cg := newContextGroup(ctx)
917 if len(dn.inodes) == 0 {
921 // Express the existence of an empty directory by
922 // adding an empty file named `\056`, which (unlike
923 // the more obvious spelling `.`) is accepted by the
924 // API's manifest validator.
925 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
928 names := dn.sortedNames()
930 // Wait for children to finish any pending write operations
931 // before locking them.
932 for _, name := range names {
933 node := dn.inodes[name]
934 if fn, ok := node.(*filenode); ok {
939 var dirnames []string
940 var filenames []string
941 for _, name := range names {
942 node := dn.inodes[name]
945 switch node := node.(type) {
947 dirnames = append(dirnames, name)
949 filenames = append(filenames, name)
951 panic(fmt.Sprintf("can't marshal inode type %T", node))
955 subdirs := make([]string, len(dirnames))
957 for i, name := range dirnames {
960 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
968 type filepart struct {
974 var fileparts []filepart
976 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
979 for _, name := range filenames {
980 node := dn.inodes[name].(*filenode)
981 if len(node.segments) == 0 {
982 fileparts = append(fileparts, filepart{name: name})
985 for _, seg := range node.segments {
986 switch seg := seg.(type) {
988 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
989 streamLen -= int64(seg.size)
991 blocks = append(blocks, seg.locator)
995 offset: streamLen + int64(seg.offset),
996 length: int64(seg.length),
998 if prev := len(fileparts) - 1; prev >= 0 &&
999 fileparts[prev].name == name &&
1000 fileparts[prev].offset+fileparts[prev].length == next.offset {
1001 fileparts[prev].length += next.length
1003 fileparts = append(fileparts, next)
1005 streamLen += int64(seg.size)
1007 // This can't happen: we
1008 // haven't unlocked since
1009 // calling flush(sync=true).
1010 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1014 var filetokens []string
1015 for _, s := range fileparts {
1016 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1018 if len(filetokens) == 0 {
1020 } else if len(blocks) == 0 {
1021 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1023 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1027 return rootdir + strings.Join(subdirs, ""), err
1030 func (dn *dirnode) loadManifest(txt string) error {
1032 streams := strings.Split(txt, "\n")
1033 if streams[len(streams)-1] != "" {
1034 return fmt.Errorf("line %d: no trailing newline", len(streams))
1036 streams = streams[:len(streams)-1]
1037 segments := []storedSegment{}
1038 for i, stream := range streams {
1040 var anyFileTokens bool
1043 segments = segments[:0]
1044 for i, token := range strings.Split(stream, " ") {
1046 dirname = manifestUnescape(token)
1049 if !strings.Contains(token, ":") {
1051 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1053 toks := strings.SplitN(token, "+", 3)
1055 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1057 length, err := strconv.ParseInt(toks[1], 10, 32)
1058 if err != nil || length < 0 {
1059 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1061 segments = append(segments, storedSegment{
1065 length: int(length),
1068 } else if len(segments) == 0 {
1069 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1072 toks := strings.SplitN(token, ":", 3)
1074 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1076 anyFileTokens = true
1078 offset, err := strconv.ParseInt(toks[0], 10, 64)
1079 if err != nil || offset < 0 {
1080 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1082 length, err := strconv.ParseInt(toks[1], 10, 64)
1083 if err != nil || length < 0 {
1084 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1086 name := dirname + "/" + manifestUnescape(toks[2])
1087 fnode, err := dn.createFileAndParents(name)
1088 if fnode == nil && err == nil && length == 0 {
1089 // Special case: an empty file used as
1090 // a marker to preserve an otherwise
1091 // empty directory in a manifest.
1094 if err != nil || (fnode == nil && length != 0) {
1095 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1097 // Map the stream offset/range coordinates to
1098 // block/offset/range coordinates and add
1099 // corresponding storedSegments to the filenode
1101 // Can't continue where we left off.
1102 // TODO: binary search instead of
1103 // rewinding all the way (but this
1104 // situation might be rare anyway)
1107 for ; segIdx < len(segments); segIdx++ {
1108 seg := segments[segIdx]
1109 next := pos + int64(seg.Len())
1110 if next <= offset || seg.Len() == 0 {
1114 if pos >= offset+length {
1119 blkOff = int(offset - pos)
1121 blkLen := seg.Len() - blkOff
1122 if pos+int64(blkOff+blkLen) > offset+length {
1123 blkLen = int(offset + length - pos - int64(blkOff))
1125 fnode.appendSegment(storedSegment{
1127 locator: seg.locator,
1132 if next > offset+length {
1138 if segIdx == len(segments) && pos < offset+length {
1139 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1143 return fmt.Errorf("line %d: no file segments", lineno)
1144 } else if len(segments) == 0 {
1145 return fmt.Errorf("line %d: no locators", lineno)
1146 } else if dirname == "" {
1147 return fmt.Errorf("line %d: no stream name", lineno)
1153 // only safe to call from loadManifest -- no locking.
1155 // If path is a "parent directory exists" marker (the last path
1156 // component is "."), the returned values are both nil.
1157 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1159 names := strings.Split(path, "/")
1160 basename := names[len(names)-1]
1161 for _, name := range names[:len(names)-1] {
1167 // can't be sure parent will be a *dirnode
1168 return nil, ErrInvalidArgument
1170 node = node.Parent()
1173 node, err = node.Child(name, func(child inode) (inode, error) {
1175 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1179 child.SetParent(node, name)
1181 } else if !child.IsDir() {
1182 return child, ErrFileExists
1191 if basename == "." {
1193 } else if !permittedName(basename) {
1194 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1197 _, err = node.Child(basename, func(child inode) (inode, error) {
1198 switch child := child.(type) {
1200 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1204 child.SetParent(node, basename)
1205 fn = child.(*filenode)
1211 return child, ErrIsDirectory
1213 return child, ErrInvalidArgument
1219 func (dn *dirnode) TreeSize() (bytes int64) {
1222 for _, i := range dn.inodes {
1223 switch i := i.(type) {
1227 bytes += i.TreeSize()
1233 type segment interface {
1236 // Return a new segment with a subsection of the data from this
1237 // one. length<0 means length=Len()-off.
1238 Slice(off int, length int) segment
1241 type memSegment struct {
1243 // If flushing is not nil and not ready/closed, then a) buf is
1244 // being shared by a pruneMemSegments goroutine, and must be
1245 // copied on write; and b) the flushing channel will close
1246 // when the goroutine finishes, whether it succeeds or not.
1247 flushing <-chan struct{}
1250 func (me *memSegment) flushingUnfinished() bool {
1251 if me.flushing == nil {
1263 func (me *memSegment) Len() int {
1267 func (me *memSegment) Slice(off, length int) segment {
1269 length = len(me.buf) - off
1271 buf := make([]byte, length)
1272 copy(buf, me.buf[off:])
1273 return &memSegment{buf: buf}
1276 func (me *memSegment) Truncate(n int) {
1277 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1280 newsize = newsize << 2
1282 newbuf := make([]byte, n, newsize)
1283 copy(newbuf, me.buf)
1284 me.buf, me.flushing = newbuf, nil
1286 // reclaim existing capacity, and zero reclaimed part
1287 oldlen := len(me.buf)
1289 for i := oldlen; i < n; i++ {
1295 func (me *memSegment) WriteAt(p []byte, off int) {
1296 if off+len(p) > len(me.buf) {
1297 panic("overflowed segment")
1299 if me.flushing != nil {
1300 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1302 copy(me.buf[off:], p)
1305 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1306 if off > int64(me.Len()) {
1310 n = copy(p, me.buf[int(off):])
1317 type storedSegment struct {
1320 size int // size of stored block (also encoded in locator)
1321 offset int // position of segment within the stored block
1322 length int // bytes in this segment (offset + length <= size)
1325 func (se storedSegment) Len() int {
1329 func (se storedSegment) Slice(n, size int) segment {
1332 if size >= 0 && se.length > size {
1338 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1339 if off > int64(se.length) {
1342 maxlen := se.length - int(off)
1343 if len(p) > maxlen {
1345 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1351 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1354 func canonicalName(name string) string {
1355 name = path.Clean("/" + name)
1356 if name == "/" || name == "./" {
1358 } else if strings.HasPrefix(name, "/") {
1364 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1366 func manifestUnescapeFunc(seq string) string {
1370 i, err := strconv.ParseUint(seq[1:], 8, 8)
1372 // Invalid escape sequence: can't unescape.
1375 return string([]byte{byte(i)})
1378 func manifestUnescape(s string) string {
1379 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1382 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1384 func manifestEscapeFunc(seq string) string {
1385 return fmt.Sprintf("\\%03o", byte(seq[0]))
1388 func manifestEscape(s string) string {
1389 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)