1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
25 maxBlockSize = 1 << 26
26 concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
29 // A CollectionFileSystem is a FileSystem that can be serialized as a
30 // manifest and stored as a collection.
31 type CollectionFileSystem interface {
34 // Flush all file data to Keep and return a snapshot of the
35 // filesystem suitable for saving as (Collection)ManifestText.
36 // Prefix (normally ".") is a top level directory, effectively
37 // prepended to all paths in the returned manifest.
38 MarshalManifest(prefix string) (string, error)
40 // Total data bytes in all files.
44 type collectionFileSystem struct {
49 storageClasses []string
50 guessSignatureTTL time.Duration
51 holdCheckChanges time.Time
52 lockCheckChanges sync.Mutex
55 // FileSystem returns a CollectionFileSystem for the collection.
56 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
57 modTime := c.ModifiedAt
61 fs := &collectionFileSystem{
63 storageClasses: c.StorageClassesDesired,
64 fileSystem: fileSystem{
65 fsBackend: keepBackend{apiClient: client, keepClient: kc},
66 thr: newThrottle(concurrentWriters),
69 fs.savedPDH.Store(c.PortableDataHash)
70 if r := c.ReplicationDesired; r != nil {
78 mode: os.ModeDir | 0755,
81 inodes: make(map[string]inode),
84 root.SetParent(root, ".")
85 if err := root.loadManifest(c.ManifestText); err != nil {
88 backdateTree(root, modTime)
93 // caller must have lock (or guarantee no concurrent accesses somehow)
94 func eachNode(n inode, ffunc func(*filenode), dfunc func(*dirnode)) {
95 switch n := n.(type) {
104 for _, n := range n.inodes {
105 eachNode(n, ffunc, dfunc)
110 // caller must have lock (or guarantee no concurrent accesses somehow)
111 func backdateTree(n inode, modTime time.Time) {
112 eachNode(n, func(fn *filenode) {
113 fn.fileinfo.modTime = modTime
114 }, func(dn *dirnode) {
115 dn.fileinfo.modTime = modTime
119 // Approximate portion of signature TTL remaining, usually between 0
120 // and 1, or negative if some signatures have expired.
121 func (fs *collectionFileSystem) signatureTimeLeft() (float64, time.Duration) {
124 earliest = now.Add(time.Hour * 24 * 7 * 365)
127 fs.fileSystem.root.RLock()
128 eachNode(fs.root, func(fn *filenode) {
131 for _, seg := range fn.segments {
132 seg, ok := seg.(storedSegment)
136 expiryTime, err := signatureExpiryTime(seg.locator)
140 if expiryTime.Before(earliest) {
141 earliest = expiryTime
143 if expiryTime.After(latest) {
148 fs.fileSystem.root.RUnlock()
151 // No signatures == 100% of TTL remaining.
155 ttl := latest.Sub(now)
156 fs.fileSystem.root.Lock()
158 if ttl > fs.guessSignatureTTL {
159 fs.guessSignatureTTL = ttl
161 ttl = fs.guessSignatureTTL
164 fs.fileSystem.root.Unlock()
166 return earliest.Sub(now).Seconds() / ttl.Seconds(), ttl
169 func (fs *collectionFileSystem) updateSignatures(newmanifest string) {
170 newLoc := map[string]string{}
171 for _, tok := range regexp.MustCompile(`\S+`).FindAllString(newmanifest, -1) {
172 if mBlkRe.MatchString(tok) {
173 newLoc[stripAllHints(tok)] = tok
176 fs.fileSystem.root.Lock()
177 defer fs.fileSystem.root.Unlock()
178 eachNode(fs.root, func(fn *filenode) {
181 for idx, seg := range fn.segments {
182 seg, ok := seg.(storedSegment)
186 loc, ok := newLoc[stripAllHints(seg.locator)]
191 fn.segments[idx] = seg
196 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
197 if name == "" || name == "." || name == ".." {
198 return nil, ErrInvalidArgument
206 mode: perm | os.ModeDir,
209 inodes: make(map[string]inode),
217 mode: perm & ^os.ModeDir,
223 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
224 return fs.rootnode().Child(name, replace)
227 func (fs *collectionFileSystem) FS() FileSystem {
231 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
232 return fs.rootnode().FileInfo()
235 func (fs *collectionFileSystem) IsDir() bool {
239 func (fs *collectionFileSystem) Lock() {
243 func (fs *collectionFileSystem) Unlock() {
244 fs.rootnode().Unlock()
247 func (fs *collectionFileSystem) RLock() {
248 fs.rootnode().RLock()
251 func (fs *collectionFileSystem) RUnlock() {
252 fs.rootnode().RUnlock()
255 func (fs *collectionFileSystem) Parent() inode {
256 return fs.rootnode().Parent()
259 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
260 return 0, ptr, ErrInvalidOperation
263 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
264 return 0, ptr, ErrInvalidOperation
267 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
268 return fs.rootnode().Readdir()
271 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
272 fs.rootnode().SetParent(parent, name)
275 func (fs *collectionFileSystem) Truncate(int64) error {
276 return ErrInvalidOperation
279 // Check for and incorporate upstream changes -- unless that has
280 // already been done recently, in which case this func is a no-op.
281 func (fs *collectionFileSystem) checkChangesOnServer() error {
282 if fs.uuid == "" && fs.savedPDH.Load() == "" {
286 // First try UUID if any, then last known PDH. Stop if all
287 // signatures are new enough.
289 for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
294 fs.lockCheckChanges.Lock()
295 if !checkingAll && fs.holdCheckChanges.After(time.Now()) {
296 fs.lockCheckChanges.Unlock()
299 remain, ttl := fs.signatureTimeLeft()
300 if remain > 0.01 && !checkingAll {
301 fs.holdCheckChanges = time.Now().Add(ttl / 100)
303 fs.lockCheckChanges.Unlock()
310 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
314 fs.updateSignatures(coll.ManifestText)
319 // Refresh signature on a single locator, if necessary. Assume caller
320 // has lock. If an update is needed, and there are any storedSegments
321 // whose signatures can be updated, start a background task to update
322 // them asynchronously when the caller releases locks.
323 func (fs *collectionFileSystem) refreshSignature(locator string) string {
324 exp, err := signatureExpiryTime(locator)
325 if err != nil || exp.Sub(time.Now()) > time.Minute {
326 // Synchronous update is not needed. Start an
327 // asynchronous update if needed.
328 go fs.checkChangesOnServer()
332 for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
337 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
341 manifests += coll.ManifestText
343 hash := stripAllHints(locator)
344 for _, tok := range regexp.MustCompile(`\S+`).FindAllString(manifests, -1) {
345 if mBlkRe.MatchString(tok) {
346 if stripAllHints(tok) == hash {
352 go fs.updateSignatures(manifests)
356 func (fs *collectionFileSystem) Sync() error {
357 err := fs.checkChangesOnServer()
364 txt, err := fs.MarshalManifest(".")
366 return fmt.Errorf("sync failed: %s", err)
368 if PortableDataHash(txt) == fs.savedPDH.Load() {
369 // No local changes since last save or initial load.
377 selectFields := []string{"uuid", "portable_data_hash"}
378 fs.lockCheckChanges.Lock()
379 remain, _ := fs.signatureTimeLeft()
380 fs.lockCheckChanges.Unlock()
382 selectFields = append(selectFields, "manifest_text")
385 err = fs.RequestAndDecode(&coll, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
386 "collection": map[string]string{
387 "manifest_text": coll.ManifestText,
389 "select": selectFields,
392 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
394 fs.updateSignatures(coll.ManifestText)
395 fs.savedPDH.Store(coll.PortableDataHash)
399 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
400 node, err := rlookup(fs.fileSystem.root, path)
404 dn, ok := node.(*dirnode)
406 return ErrNotADirectory
410 names := dn.sortedNames()
412 // Caller only wants to flush the specified dir,
413 // non-recursively. Drop subdirs from the list of
415 var filenames []string
416 for _, name := range names {
417 if _, ok := dn.inodes[name].(*filenode); ok {
418 filenames = append(filenames, name)
423 for _, name := range names {
424 child := dn.inodes[name]
428 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
431 func (fs *collectionFileSystem) MemorySize() int64 {
432 fs.fileSystem.root.Lock()
433 defer fs.fileSystem.root.Unlock()
434 return fs.fileSystem.root.(*dirnode).MemorySize()
437 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
438 fs.fileSystem.root.Lock()
439 defer fs.fileSystem.root.Unlock()
440 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
443 func (fs *collectionFileSystem) Size() int64 {
444 return fs.fileSystem.root.(*dirnode).TreeSize()
447 // filenodePtr is an offset into a file that is (usually) efficient to
448 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
450 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
451 // corresponds to file offset filenodePtr.off. Otherwise, it is
452 // necessary to reexamine len(filenode.segments[0]) etc. to find the
453 // correct segment and offset.
454 type filenodePtr struct {
461 // seek returns a ptr that is consistent with both startPtr.off and
462 // the current state of fn. The caller must already hold fn.RLock() or
465 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
470 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
472 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
473 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
476 // meaningless anyway
478 } else if ptr.off >= fn.fileinfo.size {
479 ptr.segmentIdx = len(fn.segments)
481 ptr.repacked = fn.repacked
483 } else if ptr.repacked == fn.repacked {
484 // segmentIdx and segmentOff accurately reflect
485 // ptr.off, but might have fallen off the end of a
487 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
494 ptr.repacked = fn.repacked
496 if ptr.off >= fn.fileinfo.size {
497 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
500 // Recompute segmentIdx and segmentOff. We have already
501 // established fn.fileinfo.size > ptr.off >= 0, so we don't
502 // have to deal with edge cases here.
504 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
505 // This would panic (index out of range) if
506 // fn.fileinfo.size were larger than
507 // sum(fn.segments[i].Len()) -- but that can't happen
508 // because we have ensured fn.fileinfo.size is always
510 segLen := int64(fn.segments[ptr.segmentIdx].Len())
511 if off+segLen > ptr.off {
512 ptr.segmentOff = int(ptr.off - off)
520 // filenode implements inode.
521 type filenode struct {
523 fs *collectionFileSystem
526 // number of times `segments` has changed in a
527 // way that might invalidate a filenodePtr
529 memsize int64 // bytes in memSegments
534 // caller must have lock
535 func (fn *filenode) appendSegment(e segment) {
536 fn.segments = append(fn.segments, e)
537 fn.fileinfo.size += int64(e.Len())
540 func (fn *filenode) SetParent(p inode, name string) {
544 fn.fileinfo.name = name
547 func (fn *filenode) Parent() inode {
553 func (fn *filenode) FS() FileSystem {
557 // Read reads file data from a single segment, starting at startPtr,
558 // into p. startPtr is assumed not to be up-to-date. Caller must have
560 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
561 ptr = fn.seek(startPtr)
563 err = ErrNegativeOffset
566 if ptr.segmentIdx >= len(fn.segments) {
570 if ss, ok := fn.segments[ptr.segmentIdx].(storedSegment); ok {
571 ss.locator = fn.fs.refreshSignature(ss.locator)
572 fn.segments[ptr.segmentIdx] = ss
574 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
578 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
581 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
589 func (fn *filenode) Size() int64 {
592 return fn.fileinfo.Size()
595 func (fn *filenode) FileInfo() os.FileInfo {
601 func (fn *filenode) Truncate(size int64) error {
604 return fn.truncate(size)
607 func (fn *filenode) truncate(size int64) error {
608 if size == fn.fileinfo.size {
612 if size < fn.fileinfo.size {
613 ptr := fn.seek(filenodePtr{off: size})
614 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
615 if seg, ok := fn.segments[i].(*memSegment); ok {
616 fn.memsize -= int64(seg.Len())
619 if ptr.segmentOff == 0 {
620 fn.segments = fn.segments[:ptr.segmentIdx]
622 fn.segments = fn.segments[:ptr.segmentIdx+1]
623 switch seg := fn.segments[ptr.segmentIdx].(type) {
625 seg.Truncate(ptr.segmentOff)
626 fn.memsize += int64(seg.Len())
628 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
631 fn.fileinfo.size = size
634 for size > fn.fileinfo.size {
635 grow := size - fn.fileinfo.size
638 if len(fn.segments) == 0 {
640 fn.segments = append(fn.segments, seg)
641 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
643 fn.segments = append(fn.segments, seg)
645 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
648 seg.Truncate(seg.Len() + int(grow))
649 fn.fileinfo.size += grow
655 // Write writes data from p to the file, starting at startPtr,
656 // extending the file size if necessary. Caller must have Lock.
657 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
658 if startPtr.off > fn.fileinfo.size {
659 if err = fn.truncate(startPtr.off); err != nil {
660 return 0, startPtr, err
663 ptr = fn.seek(startPtr)
665 err = ErrNegativeOffset
668 for len(p) > 0 && err == nil {
670 if len(cando) > maxBlockSize {
671 cando = cando[:maxBlockSize]
673 // Rearrange/grow fn.segments (and shrink cando if
674 // needed) such that cando can be copied to
675 // fn.segments[ptr.segmentIdx] at offset
677 cur := ptr.segmentIdx
678 prev := ptr.segmentIdx - 1
680 if cur < len(fn.segments) {
681 _, curWritable = fn.segments[cur].(*memSegment)
683 var prevAppendable bool
684 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
685 _, prevAppendable = fn.segments[prev].(*memSegment)
687 if ptr.segmentOff > 0 && !curWritable {
688 // Split a non-writable block.
689 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
690 // Truncate cur, and insert a new
693 fn.segments = append(fn.segments, nil)
694 copy(fn.segments[cur+1:], fn.segments[cur:])
696 // Split cur into two copies, truncate
697 // the one on the left, shift the one
698 // on the right, and insert a new
699 // segment between them.
700 fn.segments = append(fn.segments, nil, nil)
701 copy(fn.segments[cur+2:], fn.segments[cur:])
702 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
707 seg.Truncate(len(cando))
708 fn.memsize += int64(len(cando))
709 fn.segments[cur] = seg
710 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
715 } else if curWritable {
716 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
721 // Shrink cando if needed to fit in
723 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
724 cando = cando[:cangrow]
728 if cur == len(fn.segments) {
729 // ptr is at EOF, filesize is changing.
730 fn.fileinfo.size += int64(len(cando))
731 } else if el := fn.segments[cur].Len(); el <= len(cando) {
732 // cando is long enough that we won't
733 // need cur any more. shrink cando to
734 // be exactly as long as cur
735 // (otherwise we'd accidentally shift
736 // the effective position of all
737 // segments after cur).
739 copy(fn.segments[cur:], fn.segments[cur+1:])
740 fn.segments = fn.segments[:len(fn.segments)-1]
742 // shrink cur by the same #bytes we're growing prev
743 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
749 ptr.segmentOff = fn.segments[prev].Len()
750 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
751 fn.memsize += int64(len(cando))
755 // Insert a segment between prev and
756 // cur, and advance prev/cur.
757 fn.segments = append(fn.segments, nil)
758 if cur < len(fn.segments) {
759 copy(fn.segments[cur+1:], fn.segments[cur:])
763 // appending a new segment does
764 // not invalidate any ptrs
767 seg.Truncate(len(cando))
768 fn.memsize += int64(len(cando))
769 fn.segments[cur] = seg
773 // Finally we can copy bytes from cando to the current segment.
774 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
778 ptr.off += int64(len(cando))
779 ptr.segmentOff += len(cando)
780 if ptr.segmentOff >= maxBlockSize {
781 fn.pruneMemSegments()
783 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
788 fn.fileinfo.modTime = time.Now()
793 // Write some data out to disk to reduce memory use. Caller must have
795 func (fn *filenode) pruneMemSegments() {
796 // TODO: share code with (*dirnode)flush()
797 // TODO: pack/flush small blocks too, when fragmented
798 for idx, seg := range fn.segments {
799 seg, ok := seg.(*memSegment)
800 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
803 // Setting seg.flushing guarantees seg.buf will not be
804 // modified in place: WriteAt and Truncate will
805 // allocate a new buf instead, if necessary.
806 idx, buf := idx, seg.buf
807 done := make(chan struct{})
809 // If lots of background writes are already in
810 // progress, block here until one finishes, rather
811 // than pile up an unlimited number of buffered writes
812 // and network flush operations.
813 fn.fs.throttle().Acquire()
816 resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
818 Replicas: fn.fs.replicas,
819 StorageClasses: fn.fs.storageClasses,
821 fn.fs.throttle().Release()
824 if seg.flushing != done {
825 // A new seg.buf has been allocated.
829 // TODO: stall (or return errors from)
830 // subsequent writes until flushing
831 // starts to succeed.
834 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
835 // Segment has been dropped/moved/resized.
838 fn.memsize -= int64(len(buf))
839 fn.segments[idx] = storedSegment{
841 locator: resp.Locator,
850 // Block until all pending pruneMemSegments/flush work is
851 // finished. Caller must NOT have lock.
852 func (fn *filenode) waitPrune() {
853 var pending []<-chan struct{}
855 for _, seg := range fn.segments {
856 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
857 pending = append(pending, seg.flushing)
861 for _, p := range pending {
866 type dirnode struct {
867 fs *collectionFileSystem
871 func (dn *dirnode) FS() FileSystem {
875 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
876 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
877 gn := &getternode{Getter: func() ([]byte, error) {
880 coll.ManifestText, err = dn.fs.MarshalManifest(".")
884 coll.UUID = dn.fs.uuid
885 data, err := json.Marshal(&coll)
887 data = append(data, '\n')
891 gn.SetParent(dn, name)
894 return dn.treenode.Child(name, replace)
897 type fnSegmentRef struct {
902 // commitBlock concatenates the data from the given filenode segments
903 // (which must be *memSegments), writes the data out to Keep as a
904 // single block, and replaces the filenodes' *memSegments with
905 // storedSegments that reference the relevant portions of the new
908 // bufsize is the total data size in refs. It is used to preallocate
909 // the correct amount of memory when len(refs)>1.
911 // If sync is false, commitBlock returns right away, after starting a
912 // goroutine to do the writes, reacquire the filenodes' locks, and
913 // swap out the *memSegments. Some filenodes' segments might get
914 // modified/rearranged in the meantime, in which case commitBlock
915 // won't replace them.
917 // Caller must have write lock.
918 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
922 if err := ctx.Err(); err != nil {
925 done := make(chan struct{})
927 segs := make([]*memSegment, 0, len(refs))
928 offsets := make([]int, 0, len(refs)) // location of segment's data within block
929 for _, ref := range refs {
930 seg := ref.fn.segments[ref.idx].(*memSegment)
931 if !sync && seg.flushingUnfinished() {
932 // Let the other flushing goroutine finish. If
933 // it fails, we'll try again next time.
937 // In sync mode, we proceed regardless of
938 // whether another flush is in progress: It
939 // can't finish before we do, because we hold
940 // fn's lock until we finish our own writes.
942 offsets = append(offsets, len(block))
945 } else if block == nil {
946 block = append(make([]byte, 0, bufsize), seg.buf...)
948 block = append(block, seg.buf...)
950 segs = append(segs, seg)
952 blocksize := len(block)
953 dn.fs.throttle().Acquire()
954 errs := make(chan error, 1)
958 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
960 Replicas: dn.fs.replicas,
961 StorageClasses: dn.fs.storageClasses,
963 dn.fs.throttle().Release()
968 for idx, ref := range refs {
971 // In async mode, fn's lock was
972 // released while we were waiting for
973 // PutB(); lots of things might have
975 if len(ref.fn.segments) <= ref.idx {
976 // file segments have
977 // rearranged or changed in
981 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
982 // segment has been replaced
985 } else if seg.flushing != done {
986 // seg.buf has been replaced
991 data := ref.fn.segments[ref.idx].(*memSegment).buf
992 ref.fn.segments[ref.idx] = storedSegment{
994 locator: resp.Locator,
996 offset: offsets[idx],
999 // atomic is needed here despite caller having
1000 // lock: caller might be running concurrent
1001 // commitBlock() goroutines using the same
1002 // lock, writing different segments from the
1004 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
1016 type flushOpts struct {
1021 // flush in-memory data and remote-cluster block references (for the
1022 // children with the given names, which must be children of dn) to
1023 // local-cluster persistent storage.
1025 // Caller must have write lock on dn and the named children.
1027 // If any children are dirs, they will be flushed recursively.
1028 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
1029 cg := newContextGroup(ctx)
1032 goCommit := func(refs []fnSegmentRef, bufsize int) {
1033 cg.Go(func() error {
1034 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
1038 var pending []fnSegmentRef
1039 var pendingLen int = 0
1040 localLocator := map[string]string{}
1041 for _, name := range names {
1042 switch node := dn.inodes[name].(type) {
1044 grandchildNames := node.sortedNames()
1045 for _, grandchildName := range grandchildNames {
1046 grandchild := node.inodes[grandchildName]
1048 defer grandchild.Unlock()
1050 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
1052 for idx, seg := range node.segments {
1053 switch seg := seg.(type) {
1055 loc, ok := localLocator[seg.locator]
1058 loc, err = dn.fs.LocalLocator(seg.locator)
1062 localLocator[seg.locator] = loc
1065 node.segments[idx] = seg
1067 if seg.Len() > maxBlockSize/2 {
1068 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
1071 if pendingLen+seg.Len() > maxBlockSize {
1072 goCommit(pending, pendingLen)
1076 pending = append(pending, fnSegmentRef{node, idx})
1077 pendingLen += seg.Len()
1079 panic(fmt.Sprintf("can't sync segment type %T", seg))
1084 if opts.shortBlocks {
1085 goCommit(pending, pendingLen)
1090 // caller must have write lock.
1091 func (dn *dirnode) MemorySize() (size int64) {
1092 for _, name := range dn.sortedNames() {
1093 node := dn.inodes[name]
1096 switch node := node.(type) {
1098 size += node.MemorySize()
1100 for _, seg := range node.segments {
1101 switch seg := seg.(type) {
1103 size += int64(seg.Len())
1111 // caller must have write lock.
1112 func (dn *dirnode) sortedNames() []string {
1113 names := make([]string, 0, len(dn.inodes))
1114 for name := range dn.inodes {
1115 names = append(names, name)
1121 // caller must have write lock.
1122 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1123 cg := newContextGroup(ctx)
1126 if len(dn.inodes) == 0 {
1130 // Express the existence of an empty directory by
1131 // adding an empty file named `\056`, which (unlike
1132 // the more obvious spelling `.`) is accepted by the
1133 // API's manifest validator.
1134 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
1137 names := dn.sortedNames()
1139 // Wait for children to finish any pending write operations
1140 // before locking them.
1141 for _, name := range names {
1142 node := dn.inodes[name]
1143 if fn, ok := node.(*filenode); ok {
1148 var dirnames []string
1149 var filenames []string
1150 for _, name := range names {
1151 node := dn.inodes[name]
1154 switch node := node.(type) {
1156 dirnames = append(dirnames, name)
1158 filenames = append(filenames, name)
1160 panic(fmt.Sprintf("can't marshal inode type %T", node))
1164 subdirs := make([]string, len(dirnames))
1166 for i, name := range dirnames {
1168 cg.Go(func() error {
1169 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1175 cg.Go(func() error {
1177 type filepart struct {
1183 var fileparts []filepart
1185 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1188 for _, name := range filenames {
1189 node := dn.inodes[name].(*filenode)
1190 if len(node.segments) == 0 {
1191 fileparts = append(fileparts, filepart{name: name})
1194 for _, seg := range node.segments {
1195 switch seg := seg.(type) {
1197 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1198 streamLen -= int64(seg.size)
1200 blocks = append(blocks, seg.locator)
1204 offset: streamLen + int64(seg.offset),
1205 length: int64(seg.length),
1207 if prev := len(fileparts) - 1; prev >= 0 &&
1208 fileparts[prev].name == name &&
1209 fileparts[prev].offset+fileparts[prev].length == next.offset {
1210 fileparts[prev].length += next.length
1212 fileparts = append(fileparts, next)
1214 streamLen += int64(seg.size)
1216 // This can't happen: we
1217 // haven't unlocked since
1218 // calling flush(sync=true).
1219 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1223 var filetokens []string
1224 for _, s := range fileparts {
1225 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1227 if len(filetokens) == 0 {
1229 } else if len(blocks) == 0 {
1230 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1232 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1236 return rootdir + strings.Join(subdirs, ""), err
1239 func (dn *dirnode) loadManifest(txt string) error {
1240 streams := bytes.Split([]byte(txt), []byte{'\n'})
1241 if len(streams[len(streams)-1]) != 0 {
1242 return fmt.Errorf("line %d: no trailing newline", len(streams))
1244 streams = streams[:len(streams)-1]
1245 segments := []storedSegment{}
1246 // To reduce allocs, we reuse a single "pathparts" slice
1247 // (pre-split on "/" separators) for the duration of this
1249 var pathparts []string
1250 // To reduce allocs, we reuse a single "toks" slice of 3 byte
1252 var toks = make([][]byte, 3)
1253 // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1254 // into the toks slice rather than allocating a new one, and
1255 // returns the number of toks (1, 2, or 3).
1256 splitToToks := func(src []byte, c rune) int {
1257 c1 := bytes.IndexRune(src, c)
1262 toks[0], src = src[:c1], src[c1+1:]
1263 c2 := bytes.IndexRune(src, c)
1268 toks[1], toks[2] = src[:c2], src[c2+1:]
1271 for i, stream := range streams {
1273 var anyFileTokens bool
1276 segments = segments[:0]
1279 for i, token := range bytes.Split(stream, []byte{' '}) {
1281 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1282 streamparts = len(pathparts)
1285 if !bytes.ContainsRune(token, ':') {
1287 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1289 if splitToToks(token, '+') < 2 {
1290 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1292 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1293 if err != nil || length < 0 {
1294 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1296 segments = append(segments, storedSegment{
1297 locator: string(token),
1300 length: int(length),
1303 } else if len(segments) == 0 {
1304 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1306 if splitToToks(token, ':') != 3 {
1307 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1309 anyFileTokens = true
1311 offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1312 if err != nil || offset < 0 {
1313 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1315 length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1316 if err != nil || length < 0 {
1317 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1319 if !bytes.ContainsAny(toks[2], `\/`) {
1320 // optimization for a common case
1321 pathparts = append(pathparts[:streamparts], string(toks[2]))
1323 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1325 fnode, err := dn.createFileAndParents(pathparts)
1326 if fnode == nil && err == nil && length == 0 {
1327 // Special case: an empty file used as
1328 // a marker to preserve an otherwise
1329 // empty directory in a manifest.
1332 if err != nil || (fnode == nil && length != 0) {
1333 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1335 // Map the stream offset/range coordinates to
1336 // block/offset/range coordinates and add
1337 // corresponding storedSegments to the filenode
1339 // Can't continue where we left off.
1340 // TODO: binary search instead of
1341 // rewinding all the way (but this
1342 // situation might be rare anyway)
1345 for ; segIdx < len(segments); segIdx++ {
1346 seg := segments[segIdx]
1347 next := pos + int64(seg.Len())
1348 if next <= offset || seg.Len() == 0 {
1352 if pos >= offset+length {
1357 blkOff = int(offset - pos)
1359 blkLen := seg.Len() - blkOff
1360 if pos+int64(blkOff+blkLen) > offset+length {
1361 blkLen = int(offset + length - pos - int64(blkOff))
1363 fnode.appendSegment(storedSegment{
1365 locator: seg.locator,
1370 if next > offset+length {
1376 if segIdx == len(segments) && pos < offset+length {
1377 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1381 return fmt.Errorf("line %d: no file segments", lineno)
1382 } else if len(segments) == 0 {
1383 return fmt.Errorf("line %d: no locators", lineno)
1384 } else if streamparts == 0 {
1385 return fmt.Errorf("line %d: no stream name", lineno)
1391 // only safe to call from loadManifest -- no locking.
1393 // If path is a "parent directory exists" marker (the last path
1394 // component is "."), the returned values are both nil.
1396 // Newly added nodes have modtime==0. Caller is responsible for fixing
1397 // them with backdateTree.
1398 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1400 basename := names[len(names)-1]
1401 for _, name := range names[:len(names)-1] {
1407 // can't be sure parent will be a *dirnode
1408 return nil, ErrInvalidArgument
1410 node = node.Parent()
1414 unlock := node.Unlock
1415 node, err = node.Child(name, func(child inode) (inode, error) {
1417 // note modtime will be fixed later in backdateTree()
1418 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1422 child.SetParent(node, name)
1424 } else if !child.IsDir() {
1425 return child, ErrFileExists
1435 if basename == "." {
1437 } else if !permittedName(basename) {
1438 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1443 _, err = node.Child(basename, func(child inode) (inode, error) {
1444 switch child := child.(type) {
1446 child, err = node.FS().newNode(basename, 0755, time.Time{})
1450 child.SetParent(node, basename)
1451 fn = child.(*filenode)
1457 return child, ErrIsDirectory
1459 return child, ErrInvalidArgument
1465 func (dn *dirnode) TreeSize() (bytes int64) {
1468 for _, i := range dn.inodes {
1469 switch i := i.(type) {
1473 bytes += i.TreeSize()
1479 type segment interface {
1482 // Return a new segment with a subsection of the data from this
1483 // one. length<0 means length=Len()-off.
1484 Slice(off int, length int) segment
1487 type memSegment struct {
1489 // If flushing is not nil and not ready/closed, then a) buf is
1490 // being shared by a pruneMemSegments goroutine, and must be
1491 // copied on write; and b) the flushing channel will close
1492 // when the goroutine finishes, whether it succeeds or not.
1493 flushing <-chan struct{}
1496 func (me *memSegment) flushingUnfinished() bool {
1497 if me.flushing == nil {
1509 func (me *memSegment) Len() int {
1513 func (me *memSegment) Slice(off, length int) segment {
1515 length = len(me.buf) - off
1517 buf := make([]byte, length)
1518 copy(buf, me.buf[off:])
1519 return &memSegment{buf: buf}
1522 func (me *memSegment) Truncate(n int) {
1523 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1526 newsize = newsize << 2
1528 newbuf := make([]byte, n, newsize)
1529 copy(newbuf, me.buf)
1530 me.buf, me.flushing = newbuf, nil
1532 // reclaim existing capacity, and zero reclaimed part
1533 oldlen := len(me.buf)
1535 for i := oldlen; i < n; i++ {
1541 func (me *memSegment) WriteAt(p []byte, off int) {
1542 if off+len(p) > len(me.buf) {
1543 panic("overflowed segment")
1545 if me.flushing != nil {
1546 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1548 copy(me.buf[off:], p)
1551 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1552 if off > int64(me.Len()) {
1556 n = copy(p, me.buf[int(off):])
1563 type storedSegment struct {
1566 size int // size of stored block (also encoded in locator)
1567 offset int // position of segment within the stored block
1568 length int // bytes in this segment (offset + length <= size)
1571 func (se storedSegment) Len() int {
1575 func (se storedSegment) Slice(n, size int) segment {
1578 if size >= 0 && se.length > size {
1584 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1585 if off > int64(se.length) {
1588 maxlen := se.length - int(off)
1589 if len(p) > maxlen {
1591 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1597 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1600 func canonicalName(name string) string {
1601 name = path.Clean("/" + name)
1602 if name == "/" || name == "./" {
1604 } else if strings.HasPrefix(name, "/") {
1610 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1612 func manifestUnescapeFunc(seq string) string {
1616 i, err := strconv.ParseUint(seq[1:], 8, 8)
1618 // Invalid escape sequence: can't unescape.
1621 return string([]byte{byte(i)})
1624 func manifestUnescape(s string) string {
1625 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1628 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1630 func manifestEscapeFunc(seq string) string {
1631 return fmt.Sprintf("\\%03o", byte(seq[0]))
1634 func manifestEscape(s string) string {
1635 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)