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 // filenodePtr is an offset into a file that is (usually) efficient to
197 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
199 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
200 // corresponds to file offset filenodePtr.off. Otherwise, it is
201 // necessary to reexamine len(filenode.segments[0]) etc. to find the
202 // correct segment and offset.
203 type filenodePtr struct {
210 // seek returns a ptr that is consistent with both startPtr.off and
211 // the current state of fn. The caller must already hold fn.RLock() or
214 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
219 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
221 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
222 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
225 // meaningless anyway
227 } else if ptr.off >= fn.fileinfo.size {
228 ptr.segmentIdx = len(fn.segments)
230 ptr.repacked = fn.repacked
232 } else if ptr.repacked == fn.repacked {
233 // segmentIdx and segmentOff accurately reflect
234 // ptr.off, but might have fallen off the end of a
236 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
243 ptr.repacked = fn.repacked
245 if ptr.off >= fn.fileinfo.size {
246 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
249 // Recompute segmentIdx and segmentOff. We have already
250 // established fn.fileinfo.size > ptr.off >= 0, so we don't
251 // have to deal with edge cases here.
253 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
254 // This would panic (index out of range) if
255 // fn.fileinfo.size were larger than
256 // sum(fn.segments[i].Len()) -- but that can't happen
257 // because we have ensured fn.fileinfo.size is always
259 segLen := int64(fn.segments[ptr.segmentIdx].Len())
260 if off+segLen > ptr.off {
261 ptr.segmentOff = int(ptr.off - off)
269 // filenode implements inode.
270 type filenode struct {
275 // number of times `segments` has changed in a
276 // way that might invalidate a filenodePtr
278 memsize int64 // bytes in memSegments
283 // caller must have lock
284 func (fn *filenode) appendSegment(e segment) {
285 fn.segments = append(fn.segments, e)
286 fn.fileinfo.size += int64(e.Len())
289 func (fn *filenode) SetParent(p inode, name string) {
293 fn.fileinfo.name = name
296 func (fn *filenode) Parent() inode {
302 func (fn *filenode) FS() FileSystem {
306 // Read reads file data from a single segment, starting at startPtr,
307 // into p. startPtr is assumed not to be up-to-date. Caller must have
309 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
310 ptr = fn.seek(startPtr)
312 err = ErrNegativeOffset
315 if ptr.segmentIdx >= len(fn.segments) {
319 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
323 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
326 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
334 func (fn *filenode) Size() int64 {
337 return fn.fileinfo.Size()
340 func (fn *filenode) FileInfo() os.FileInfo {
346 func (fn *filenode) Truncate(size int64) error {
349 return fn.truncate(size)
352 func (fn *filenode) truncate(size int64) error {
353 if size == fn.fileinfo.size {
357 if size < fn.fileinfo.size {
358 ptr := fn.seek(filenodePtr{off: size})
359 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
360 if seg, ok := fn.segments[i].(*memSegment); ok {
361 fn.memsize -= int64(seg.Len())
364 if ptr.segmentOff == 0 {
365 fn.segments = fn.segments[:ptr.segmentIdx]
367 fn.segments = fn.segments[:ptr.segmentIdx+1]
368 switch seg := fn.segments[ptr.segmentIdx].(type) {
370 seg.Truncate(ptr.segmentOff)
371 fn.memsize += int64(seg.Len())
373 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
376 fn.fileinfo.size = size
379 for size > fn.fileinfo.size {
380 grow := size - fn.fileinfo.size
383 if len(fn.segments) == 0 {
385 fn.segments = append(fn.segments, seg)
386 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
388 fn.segments = append(fn.segments, seg)
390 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
393 seg.Truncate(seg.Len() + int(grow))
394 fn.fileinfo.size += grow
400 // Write writes data from p to the file, starting at startPtr,
401 // extending the file size if necessary. Caller must have Lock.
402 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
403 if startPtr.off > fn.fileinfo.size {
404 if err = fn.truncate(startPtr.off); err != nil {
405 return 0, startPtr, err
408 ptr = fn.seek(startPtr)
410 err = ErrNegativeOffset
413 for len(p) > 0 && err == nil {
415 if len(cando) > maxBlockSize {
416 cando = cando[:maxBlockSize]
418 // Rearrange/grow fn.segments (and shrink cando if
419 // needed) such that cando can be copied to
420 // fn.segments[ptr.segmentIdx] at offset
422 cur := ptr.segmentIdx
423 prev := ptr.segmentIdx - 1
425 if cur < len(fn.segments) {
426 _, curWritable = fn.segments[cur].(*memSegment)
428 var prevAppendable bool
429 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
430 _, prevAppendable = fn.segments[prev].(*memSegment)
432 if ptr.segmentOff > 0 && !curWritable {
433 // Split a non-writable block.
434 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
435 // Truncate cur, and insert a new
438 fn.segments = append(fn.segments, nil)
439 copy(fn.segments[cur+1:], fn.segments[cur:])
441 // Split cur into two copies, truncate
442 // the one on the left, shift the one
443 // on the right, and insert a new
444 // segment between them.
445 fn.segments = append(fn.segments, nil, nil)
446 copy(fn.segments[cur+2:], fn.segments[cur:])
447 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
452 seg.Truncate(len(cando))
453 fn.memsize += int64(len(cando))
454 fn.segments[cur] = seg
455 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
460 } else if curWritable {
461 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
466 // Shrink cando if needed to fit in
468 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
469 cando = cando[:cangrow]
473 if cur == len(fn.segments) {
474 // ptr is at EOF, filesize is changing.
475 fn.fileinfo.size += int64(len(cando))
476 } else if el := fn.segments[cur].Len(); el <= len(cando) {
477 // cando is long enough that we won't
478 // need cur any more. shrink cando to
479 // be exactly as long as cur
480 // (otherwise we'd accidentally shift
481 // the effective position of all
482 // segments after cur).
484 copy(fn.segments[cur:], fn.segments[cur+1:])
485 fn.segments = fn.segments[:len(fn.segments)-1]
487 // shrink cur by the same #bytes we're growing prev
488 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
494 ptr.segmentOff = fn.segments[prev].Len()
495 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
496 fn.memsize += int64(len(cando))
500 // Insert a segment between prev and
501 // cur, and advance prev/cur.
502 fn.segments = append(fn.segments, nil)
503 if cur < len(fn.segments) {
504 copy(fn.segments[cur+1:], fn.segments[cur:])
508 // appending a new segment does
509 // not invalidate any ptrs
512 seg.Truncate(len(cando))
513 fn.memsize += int64(len(cando))
514 fn.segments[cur] = seg
520 // Finally we can copy bytes from cando to the current segment.
521 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
525 ptr.off += int64(len(cando))
526 ptr.segmentOff += len(cando)
527 if ptr.segmentOff >= maxBlockSize {
528 fn.pruneMemSegments()
530 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
535 fn.fileinfo.modTime = time.Now()
540 // Write some data out to disk to reduce memory use. Caller must have
542 func (fn *filenode) pruneMemSegments() {
543 // TODO: share code with (*dirnode)flush()
544 // TODO: pack/flush small blocks too, when fragmented
545 for idx, seg := range fn.segments {
546 seg, ok := seg.(*memSegment)
547 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
550 // Setting seg.flushing guarantees seg.buf will not be
551 // modified in place: WriteAt and Truncate will
552 // allocate a new buf instead, if necessary.
553 idx, buf := idx, seg.buf
554 done := make(chan struct{})
556 // If lots of background writes are already in
557 // progress, block here until one finishes, rather
558 // than pile up an unlimited number of buffered writes
559 // and network flush operations.
560 fn.fs.throttle().Acquire()
563 locator, _, err := fn.FS().PutB(buf)
564 fn.fs.throttle().Release()
567 if seg.flushing != done {
568 // 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 !sync && seg.flushingUnfinished() {
674 // Let the other flushing goroutine finish. If
675 // it fails, we'll try again next time.
679 // In sync mode, we proceed regardless of
680 // whether another flush is in progress: It
681 // can't finish before we do, because we hold
682 // fn's lock until we finish our own writes.
685 offsets = append(offsets, len(block))
688 } else if block == nil {
689 block = append(make([]byte, 0, bufsize), seg.buf...)
691 block = append(block, seg.buf...)
693 segs = append(segs, seg)
695 blocksize := len(block)
696 dn.fs.throttle().Acquire()
697 errs := make(chan error, 1)
701 locator, _, err := dn.fs.PutB(block)
702 dn.fs.throttle().Release()
707 for idx, ref := range refs {
710 // In async mode, fn's lock was
711 // released while we were waiting for
712 // PutB(); lots of things might have
714 if len(ref.fn.segments) <= ref.idx {
715 // file segments have
716 // rearranged or changed in
720 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
721 // segment has been replaced
724 } else if seg.flushing != done {
725 // seg.buf has been replaced
730 data := ref.fn.segments[ref.idx].(*memSegment).buf
731 ref.fn.segments[ref.idx] = storedSegment{
735 offset: offsets[idx],
738 // atomic is needed here despite caller having
739 // lock: caller might be running concurrent
740 // commitBlock() goroutines using the same
741 // lock, writing different segments from the
743 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
756 type flushOpts struct {
761 // flush in-memory data and remote-cluster block references (for the
762 // children with the given names, which must be children of dn) to
763 // local-cluster persistent storage.
765 // Caller must have write lock on dn and the named children.
767 // If any children are dirs, they will be flushed recursively.
768 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
769 cg := newContextGroup(ctx)
772 goCommit := func(refs []fnSegmentRef, bufsize int) {
774 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
778 var pending []fnSegmentRef
779 var pendingLen int = 0
780 localLocator := map[string]string{}
781 for _, name := range names {
782 switch node := dn.inodes[name].(type) {
784 grandchildNames := node.sortedNames()
785 for _, grandchildName := range grandchildNames {
786 grandchild := node.inodes[grandchildName]
788 defer grandchild.Unlock()
790 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
792 for idx, seg := range node.segments {
793 switch seg := seg.(type) {
795 loc, ok := localLocator[seg.locator]
798 loc, err = dn.fs.LocalLocator(seg.locator)
802 localLocator[seg.locator] = loc
805 node.segments[idx] = seg
807 if seg.Len() > maxBlockSize/2 {
808 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
811 if pendingLen+seg.Len() > maxBlockSize {
812 goCommit(pending, pendingLen)
816 pending = append(pending, fnSegmentRef{node, idx})
817 pendingLen += seg.Len()
819 panic(fmt.Sprintf("can't sync segment type %T", seg))
824 if opts.shortBlocks {
825 goCommit(pending, pendingLen)
830 // caller must have write lock.
831 func (dn *dirnode) memorySize() (size int64) {
832 for _, name := range dn.sortedNames() {
833 node := dn.inodes[name]
836 switch node := node.(type) {
838 size += node.memorySize()
840 for _, seg := range node.segments {
841 switch seg := seg.(type) {
843 size += int64(seg.Len())
851 // caller must have write lock.
852 func (dn *dirnode) sortedNames() []string {
853 names := make([]string, 0, len(dn.inodes))
854 for name := range dn.inodes {
855 names = append(names, name)
861 // caller must have write lock.
862 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
863 cg := newContextGroup(ctx)
866 if len(dn.inodes) == 0 {
870 // Express the existence of an empty directory by
871 // adding an empty file named `\056`, which (unlike
872 // the more obvious spelling `.`) is accepted by the
873 // API's manifest validator.
874 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
877 names := dn.sortedNames()
879 // Wait for children to finish any pending write operations
880 // before locking them.
881 for _, name := range names {
882 node := dn.inodes[name]
883 if fn, ok := node.(*filenode); ok {
888 var dirnames []string
889 var filenames []string
890 for _, name := range names {
891 node := dn.inodes[name]
894 switch node := node.(type) {
896 dirnames = append(dirnames, name)
898 filenames = append(filenames, name)
900 panic(fmt.Sprintf("can't marshal inode type %T", node))
904 subdirs := make([]string, len(dirnames))
906 for i, name := range dirnames {
909 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
917 type filepart struct {
923 var fileparts []filepart
925 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
928 for _, name := range filenames {
929 node := dn.inodes[name].(*filenode)
930 if len(node.segments) == 0 {
931 fileparts = append(fileparts, filepart{name: name})
934 for _, seg := range node.segments {
935 switch seg := seg.(type) {
937 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
938 streamLen -= int64(seg.size)
940 blocks = append(blocks, seg.locator)
944 offset: streamLen + int64(seg.offset),
945 length: int64(seg.length),
947 if prev := len(fileparts) - 1; prev >= 0 &&
948 fileparts[prev].name == name &&
949 fileparts[prev].offset+fileparts[prev].length == next.offset {
950 fileparts[prev].length += next.length
952 fileparts = append(fileparts, next)
954 streamLen += int64(seg.size)
956 // This can't happen: we
957 // haven't unlocked since
958 // calling flush(sync=true).
959 panic(fmt.Sprintf("can't marshal segment type %T", seg))
963 var filetokens []string
964 for _, s := range fileparts {
965 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
967 if len(filetokens) == 0 {
969 } else if len(blocks) == 0 {
970 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
972 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
976 return rootdir + strings.Join(subdirs, ""), err
979 func (dn *dirnode) loadManifest(txt string) error {
981 streams := strings.Split(txt, "\n")
982 if streams[len(streams)-1] != "" {
983 return fmt.Errorf("line %d: no trailing newline", len(streams))
985 streams = streams[:len(streams)-1]
986 segments := []storedSegment{}
987 for i, stream := range streams {
989 var anyFileTokens bool
992 segments = segments[:0]
993 for i, token := range strings.Split(stream, " ") {
995 dirname = manifestUnescape(token)
998 if !strings.Contains(token, ":") {
1000 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1002 toks := strings.SplitN(token, "+", 3)
1004 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1006 length, err := strconv.ParseInt(toks[1], 10, 32)
1007 if err != nil || length < 0 {
1008 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1010 segments = append(segments, storedSegment{
1014 length: int(length),
1017 } else if len(segments) == 0 {
1018 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1021 toks := strings.SplitN(token, ":", 3)
1023 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1025 anyFileTokens = true
1027 offset, err := strconv.ParseInt(toks[0], 10, 64)
1028 if err != nil || offset < 0 {
1029 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1031 length, err := strconv.ParseInt(toks[1], 10, 64)
1032 if err != nil || length < 0 {
1033 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1035 name := dirname + "/" + manifestUnescape(toks[2])
1036 fnode, err := dn.createFileAndParents(name)
1037 if fnode == nil && err == nil && length == 0 {
1038 // Special case: an empty file used as
1039 // a marker to preserve an otherwise
1040 // empty directory in a manifest.
1043 if err != nil || (fnode == nil && length != 0) {
1044 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1046 // Map the stream offset/range coordinates to
1047 // block/offset/range coordinates and add
1048 // corresponding storedSegments to the filenode
1050 // Can't continue where we left off.
1051 // TODO: binary search instead of
1052 // rewinding all the way (but this
1053 // situation might be rare anyway)
1056 for next := int64(0); segIdx < len(segments); segIdx++ {
1057 seg := segments[segIdx]
1058 next = pos + int64(seg.Len())
1059 if next <= offset || seg.Len() == 0 {
1063 if pos >= offset+length {
1068 blkOff = int(offset - pos)
1070 blkLen := seg.Len() - blkOff
1071 if pos+int64(blkOff+blkLen) > offset+length {
1072 blkLen = int(offset + length - pos - int64(blkOff))
1074 fnode.appendSegment(storedSegment{
1076 locator: seg.locator,
1081 if next > offset+length {
1087 if segIdx == len(segments) && pos < offset+length {
1088 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1092 return fmt.Errorf("line %d: no file segments", lineno)
1093 } else if len(segments) == 0 {
1094 return fmt.Errorf("line %d: no locators", lineno)
1095 } else if dirname == "" {
1096 return fmt.Errorf("line %d: no stream name", lineno)
1102 // only safe to call from loadManifest -- no locking.
1104 // If path is a "parent directory exists" marker (the last path
1105 // component is "."), the returned values are both nil.
1106 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1108 names := strings.Split(path, "/")
1109 basename := names[len(names)-1]
1110 for _, name := range names[:len(names)-1] {
1116 // can't be sure parent will be a *dirnode
1117 return nil, ErrInvalidArgument
1119 node = node.Parent()
1122 node, err = node.Child(name, func(child inode) (inode, error) {
1124 child, err := node.FS().newNode(name, 0755|os.ModeDir, node.Parent().FileInfo().ModTime())
1128 child.SetParent(node, name)
1130 } else if !child.IsDir() {
1131 return child, ErrFileExists
1140 if basename == "." {
1142 } else if !permittedName(basename) {
1143 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1146 _, err = node.Child(basename, func(child inode) (inode, error) {
1147 switch child := child.(type) {
1149 child, err = node.FS().newNode(basename, 0755, node.FileInfo().ModTime())
1153 child.SetParent(node, basename)
1154 fn = child.(*filenode)
1160 return child, ErrIsDirectory
1162 return child, ErrInvalidArgument
1168 func (dn *dirnode) TreeSize() (bytes int64) {
1171 for _, i := range dn.inodes {
1172 switch i := i.(type) {
1176 bytes += i.TreeSize()
1182 type segment interface {
1185 // Return a new segment with a subsection of the data from this
1186 // one. length<0 means length=Len()-off.
1187 Slice(off int, length int) segment
1190 type memSegment struct {
1192 // If flushing is not nil and not ready/closed, then a) buf is
1193 // being shared by a pruneMemSegments goroutine, and must be
1194 // copied on write; and b) the flushing channel will close
1195 // when the goroutine finishes, whether it succeeds or not.
1196 flushing <-chan struct{}
1199 func (me *memSegment) flushingUnfinished() bool {
1200 if me.flushing == nil {
1212 func (me *memSegment) Len() int {
1216 func (me *memSegment) Slice(off, length int) segment {
1218 length = len(me.buf) - off
1220 buf := make([]byte, length)
1221 copy(buf, me.buf[off:])
1222 return &memSegment{buf: buf}
1225 func (me *memSegment) Truncate(n int) {
1226 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1229 newsize = newsize << 2
1231 newbuf := make([]byte, n, newsize)
1232 copy(newbuf, me.buf)
1233 me.buf, me.flushing = newbuf, nil
1235 // reclaim existing capacity, and zero reclaimed part
1236 oldlen := len(me.buf)
1238 for i := oldlen; i < n; i++ {
1244 func (me *memSegment) WriteAt(p []byte, off int) {
1245 if off+len(p) > len(me.buf) {
1246 panic("overflowed segment")
1248 if me.flushing != nil {
1249 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1251 copy(me.buf[off:], p)
1254 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1255 if off > int64(me.Len()) {
1259 n = copy(p, me.buf[int(off):])
1266 type storedSegment struct {
1269 size int // size of stored block (also encoded in locator)
1270 offset int // position of segment within the stored block
1271 length int // bytes in this segment (offset + length <= size)
1274 func (se storedSegment) Len() int {
1278 func (se storedSegment) Slice(n, size int) segment {
1281 if size >= 0 && se.length > size {
1287 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1288 if off > int64(se.length) {
1291 maxlen := se.length - int(off)
1292 if len(p) > maxlen {
1294 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1300 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1303 func canonicalName(name string) string {
1304 name = path.Clean("/" + name)
1305 if name == "/" || name == "./" {
1307 } else if strings.HasPrefix(name, "/") {
1313 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1315 func manifestUnescapeFunc(seq string) string {
1319 i, err := strconv.ParseUint(seq[1:], 8, 8)
1321 // Invalid escape sequence: can't unescape.
1324 return string([]byte{byte(i)})
1327 func manifestUnescape(s string) string {
1328 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1331 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1333 func manifestEscapeFunc(seq string) string {
1334 return fmt.Sprintf("\\%03o", byte(seq[0]))
1337 func manifestEscape(s string) string {
1338 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)