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 tracks a lower bound for the server's
51 // configured BlobSigningTTL. The guess is initially zero, and
52 // increases when we come across a signature with an expiry
53 // time further in the future than the previous guess.
55 // When the guessed TTL is much smaller than the real TTL,
56 // preemptive signature refresh is delayed or missed entirely,
58 guessSignatureTTL time.Duration
59 holdCheckChanges time.Time
60 lockCheckChanges sync.Mutex
63 // FileSystem returns a CollectionFileSystem for the collection.
64 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
65 modTime := c.ModifiedAt
69 fs := &collectionFileSystem{
71 storageClasses: c.StorageClassesDesired,
72 fileSystem: fileSystem{
73 fsBackend: keepBackend{apiClient: client, keepClient: kc},
74 thr: newThrottle(concurrentWriters),
77 fs.savedPDH.Store(c.PortableDataHash)
78 if r := c.ReplicationDesired; r != nil {
86 mode: os.ModeDir | 0755,
89 inodes: make(map[string]inode),
92 root.SetParent(root, ".")
93 if err := root.loadManifest(c.ManifestText); err != nil {
96 backdateTree(root, modTime)
101 // caller must have lock (or guarantee no concurrent accesses somehow)
102 func eachNode(n inode, ffunc func(*filenode), dfunc func(*dirnode)) {
103 switch n := n.(type) {
112 for _, n := range n.inodes {
113 eachNode(n, ffunc, dfunc)
118 // caller must have lock (or guarantee no concurrent accesses somehow)
119 func backdateTree(n inode, modTime time.Time) {
120 eachNode(n, func(fn *filenode) {
121 fn.fileinfo.modTime = modTime
122 }, func(dn *dirnode) {
123 dn.fileinfo.modTime = modTime
127 // Approximate portion of signature TTL remaining, usually between 0
128 // and 1, or negative if some signatures have expired.
129 func (fs *collectionFileSystem) signatureTimeLeft() (float64, time.Duration) {
132 earliest = now.Add(time.Hour * 24 * 7 * 365)
135 fs.fileSystem.root.RLock()
136 eachNode(fs.root, func(fn *filenode) {
139 for _, seg := range fn.segments {
140 seg, ok := seg.(storedSegment)
144 expiryTime, err := signatureExpiryTime(seg.locator)
148 if expiryTime.Before(earliest) {
149 earliest = expiryTime
151 if expiryTime.After(latest) {
156 fs.fileSystem.root.RUnlock()
159 // No signatures == 100% of TTL remaining.
163 ttl := latest.Sub(now)
164 fs.fileSystem.root.Lock()
166 if ttl > fs.guessSignatureTTL {
167 // ttl is closer to the real TTL than
168 // guessSignatureTTL.
169 fs.guessSignatureTTL = ttl
171 // Use the previous best guess to compute the
172 // portion remaining (below, after unlocking
174 ttl = fs.guessSignatureTTL
177 fs.fileSystem.root.Unlock()
179 return earliest.Sub(now).Seconds() / ttl.Seconds(), ttl
182 func (fs *collectionFileSystem) updateSignatures(newmanifest string) {
183 newLoc := map[string]string{}
184 for _, tok := range regexp.MustCompile(`\S+`).FindAllString(newmanifest, -1) {
185 if mBlkRe.MatchString(tok) {
186 newLoc[stripAllHints(tok)] = tok
189 fs.fileSystem.root.Lock()
190 defer fs.fileSystem.root.Unlock()
191 eachNode(fs.root, func(fn *filenode) {
194 for idx, seg := range fn.segments {
195 seg, ok := seg.(storedSegment)
199 loc, ok := newLoc[stripAllHints(seg.locator)]
204 fn.segments[idx] = seg
209 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
210 if name == "" || name == "." || name == ".." {
211 return nil, ErrInvalidArgument
219 mode: perm | os.ModeDir,
222 inodes: make(map[string]inode),
230 mode: perm & ^os.ModeDir,
236 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
237 return fs.rootnode().Child(name, replace)
240 func (fs *collectionFileSystem) FS() FileSystem {
244 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
245 return fs.rootnode().FileInfo()
248 func (fs *collectionFileSystem) IsDir() bool {
252 func (fs *collectionFileSystem) Lock() {
256 func (fs *collectionFileSystem) Unlock() {
257 fs.rootnode().Unlock()
260 func (fs *collectionFileSystem) RLock() {
261 fs.rootnode().RLock()
264 func (fs *collectionFileSystem) RUnlock() {
265 fs.rootnode().RUnlock()
268 func (fs *collectionFileSystem) Parent() inode {
269 return fs.rootnode().Parent()
272 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
273 return 0, ptr, ErrInvalidOperation
276 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
277 return 0, ptr, ErrInvalidOperation
280 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
281 return fs.rootnode().Readdir()
284 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
285 fs.rootnode().SetParent(parent, name)
288 func (fs *collectionFileSystem) Truncate(int64) error {
289 return ErrInvalidOperation
292 // Check for and incorporate upstream changes -- unless that has
293 // already been done recently, in which case this func is a no-op.
294 func (fs *collectionFileSystem) checkChangesOnServer() error {
295 if fs.uuid == "" && fs.savedPDH.Load() == "" {
299 // First try UUID if any, then last known PDH. Stop if all
300 // signatures are new enough.
302 for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
307 fs.lockCheckChanges.Lock()
308 if !checkingAll && fs.holdCheckChanges.After(time.Now()) {
309 fs.lockCheckChanges.Unlock()
312 remain, ttl := fs.signatureTimeLeft()
313 if remain > 0.01 && !checkingAll {
314 fs.holdCheckChanges = time.Now().Add(ttl / 100)
316 fs.lockCheckChanges.Unlock()
323 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
327 fs.updateSignatures(coll.ManifestText)
332 // Refresh signature on a single locator, if necessary. Assume caller
333 // has lock. If an update is needed, and there are any storedSegments
334 // whose signatures can be updated, start a background task to update
335 // them asynchronously when the caller releases locks.
336 func (fs *collectionFileSystem) refreshSignature(locator string) string {
337 exp, err := signatureExpiryTime(locator)
338 if err != nil || exp.Sub(time.Now()) > time.Minute {
339 // Synchronous update is not needed. Start an
340 // asynchronous update if needed.
341 go fs.checkChangesOnServer()
345 for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
350 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
354 manifests += coll.ManifestText
356 hash := stripAllHints(locator)
357 for _, tok := range regexp.MustCompile(`\S+`).FindAllString(manifests, -1) {
358 if mBlkRe.MatchString(tok) {
359 if stripAllHints(tok) == hash {
365 go fs.updateSignatures(manifests)
369 func (fs *collectionFileSystem) Sync() error {
370 err := fs.checkChangesOnServer()
377 txt, err := fs.MarshalManifest(".")
379 return fmt.Errorf("sync failed: %s", err)
381 if PortableDataHash(txt) == fs.savedPDH.Load() {
382 // No local changes since last save or initial load.
390 selectFields := []string{"uuid", "portable_data_hash"}
391 fs.lockCheckChanges.Lock()
392 remain, _ := fs.signatureTimeLeft()
393 fs.lockCheckChanges.Unlock()
395 selectFields = append(selectFields, "manifest_text")
398 err = fs.RequestAndDecode(&coll, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
399 "collection": map[string]string{
400 "manifest_text": coll.ManifestText,
402 "select": selectFields,
405 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
407 fs.updateSignatures(coll.ManifestText)
408 fs.savedPDH.Store(coll.PortableDataHash)
412 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
413 node, err := rlookup(fs.fileSystem.root, path)
417 dn, ok := node.(*dirnode)
419 return ErrNotADirectory
423 names := dn.sortedNames()
425 // Caller only wants to flush the specified dir,
426 // non-recursively. Drop subdirs from the list of
428 var filenames []string
429 for _, name := range names {
430 if _, ok := dn.inodes[name].(*filenode); ok {
431 filenames = append(filenames, name)
436 for _, name := range names {
437 child := dn.inodes[name]
441 return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
444 func (fs *collectionFileSystem) MemorySize() int64 {
445 fs.fileSystem.root.Lock()
446 defer fs.fileSystem.root.Unlock()
447 return fs.fileSystem.root.(*dirnode).MemorySize()
450 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
451 fs.fileSystem.root.Lock()
452 defer fs.fileSystem.root.Unlock()
453 return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
456 func (fs *collectionFileSystem) Size() int64 {
457 return fs.fileSystem.root.(*dirnode).TreeSize()
460 func (fs *collectionFileSystem) Snapshot() (inode, error) {
461 return fs.fileSystem.root.Snapshot()
464 func (fs *collectionFileSystem) Splice(r inode) error {
465 return fs.fileSystem.root.Splice(r)
468 // filenodePtr is an offset into a file that is (usually) efficient to
469 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
471 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
472 // corresponds to file offset filenodePtr.off. Otherwise, it is
473 // necessary to reexamine len(filenode.segments[0]) etc. to find the
474 // correct segment and offset.
475 type filenodePtr struct {
482 // seek returns a ptr that is consistent with both startPtr.off and
483 // the current state of fn. The caller must already hold fn.RLock() or
486 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
491 // ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
493 // filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
494 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
497 // meaningless anyway
499 } else if ptr.off >= fn.fileinfo.size {
500 ptr.segmentIdx = len(fn.segments)
502 ptr.repacked = fn.repacked
504 } else if ptr.repacked == fn.repacked {
505 // segmentIdx and segmentOff accurately reflect
506 // ptr.off, but might have fallen off the end of a
508 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
515 ptr.repacked = fn.repacked
517 if ptr.off >= fn.fileinfo.size {
518 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
521 // Recompute segmentIdx and segmentOff. We have already
522 // established fn.fileinfo.size > ptr.off >= 0, so we don't
523 // have to deal with edge cases here.
525 for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
526 // This would panic (index out of range) if
527 // fn.fileinfo.size were larger than
528 // sum(fn.segments[i].Len()) -- but that can't happen
529 // because we have ensured fn.fileinfo.size is always
531 segLen := int64(fn.segments[ptr.segmentIdx].Len())
532 if off+segLen > ptr.off {
533 ptr.segmentOff = int(ptr.off - off)
541 // filenode implements inode.
542 type filenode struct {
544 fs *collectionFileSystem
547 // number of times `segments` has changed in a
548 // way that might invalidate a filenodePtr
550 memsize int64 // bytes in memSegments
555 // caller must have lock
556 func (fn *filenode) appendSegment(e segment) {
557 fn.segments = append(fn.segments, e)
558 fn.fileinfo.size += int64(e.Len())
561 func (fn *filenode) SetParent(p inode, name string) {
565 fn.fileinfo.name = name
568 func (fn *filenode) Parent() inode {
574 func (fn *filenode) FS() FileSystem {
578 // Read reads file data from a single segment, starting at startPtr,
579 // into p. startPtr is assumed not to be up-to-date. Caller must have
581 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
582 ptr = fn.seek(startPtr)
584 err = ErrNegativeOffset
587 if ptr.segmentIdx >= len(fn.segments) {
591 if ss, ok := fn.segments[ptr.segmentIdx].(storedSegment); ok {
592 ss.locator = fn.fs.refreshSignature(ss.locator)
593 fn.segments[ptr.segmentIdx] = ss
595 n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
599 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
602 if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
610 func (fn *filenode) Size() int64 {
613 return fn.fileinfo.Size()
616 func (fn *filenode) FileInfo() os.FileInfo {
622 func (fn *filenode) Truncate(size int64) error {
625 return fn.truncate(size)
628 func (fn *filenode) truncate(size int64) error {
629 if size == fn.fileinfo.size {
633 if size < fn.fileinfo.size {
634 ptr := fn.seek(filenodePtr{off: size})
635 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
636 if seg, ok := fn.segments[i].(*memSegment); ok {
637 fn.memsize -= int64(seg.Len())
640 if ptr.segmentOff == 0 {
641 fn.segments = fn.segments[:ptr.segmentIdx]
643 fn.segments = fn.segments[:ptr.segmentIdx+1]
644 switch seg := fn.segments[ptr.segmentIdx].(type) {
646 seg.Truncate(ptr.segmentOff)
647 fn.memsize += int64(seg.Len())
649 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
652 fn.fileinfo.size = size
655 for size > fn.fileinfo.size {
656 grow := size - fn.fileinfo.size
659 if len(fn.segments) == 0 {
661 fn.segments = append(fn.segments, seg)
662 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
664 fn.segments = append(fn.segments, seg)
666 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
669 seg.Truncate(seg.Len() + int(grow))
670 fn.fileinfo.size += grow
676 // Write writes data from p to the file, starting at startPtr,
677 // extending the file size if necessary. Caller must have Lock.
678 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
679 if startPtr.off > fn.fileinfo.size {
680 if err = fn.truncate(startPtr.off); err != nil {
681 return 0, startPtr, err
684 ptr = fn.seek(startPtr)
686 err = ErrNegativeOffset
689 for len(p) > 0 && err == nil {
691 if len(cando) > maxBlockSize {
692 cando = cando[:maxBlockSize]
694 // Rearrange/grow fn.segments (and shrink cando if
695 // needed) such that cando can be copied to
696 // fn.segments[ptr.segmentIdx] at offset
698 cur := ptr.segmentIdx
699 prev := ptr.segmentIdx - 1
701 if cur < len(fn.segments) {
702 _, curWritable = fn.segments[cur].(*memSegment)
704 var prevAppendable bool
705 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
706 _, prevAppendable = fn.segments[prev].(*memSegment)
708 if ptr.segmentOff > 0 && !curWritable {
709 // Split a non-writable block.
710 if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
711 // Truncate cur, and insert a new
714 fn.segments = append(fn.segments, nil)
715 copy(fn.segments[cur+1:], fn.segments[cur:])
717 // Split cur into two copies, truncate
718 // the one on the left, shift the one
719 // on the right, and insert a new
720 // segment between them.
721 fn.segments = append(fn.segments, nil, nil)
722 copy(fn.segments[cur+2:], fn.segments[cur:])
723 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
728 seg.Truncate(len(cando))
729 fn.memsize += int64(len(cando))
730 fn.segments[cur] = seg
731 fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
736 } else if curWritable {
737 if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
742 // Shrink cando if needed to fit in
744 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
745 cando = cando[:cangrow]
749 if cur == len(fn.segments) {
750 // ptr is at EOF, filesize is changing.
751 fn.fileinfo.size += int64(len(cando))
752 } else if el := fn.segments[cur].Len(); el <= len(cando) {
753 // cando is long enough that we won't
754 // need cur any more. shrink cando to
755 // be exactly as long as cur
756 // (otherwise we'd accidentally shift
757 // the effective position of all
758 // segments after cur).
760 copy(fn.segments[cur:], fn.segments[cur+1:])
761 fn.segments = fn.segments[:len(fn.segments)-1]
763 // shrink cur by the same #bytes we're growing prev
764 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
770 ptr.segmentOff = fn.segments[prev].Len()
771 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
772 fn.memsize += int64(len(cando))
776 // Insert a segment between prev and
777 // cur, and advance prev/cur.
778 fn.segments = append(fn.segments, nil)
779 if cur < len(fn.segments) {
780 copy(fn.segments[cur+1:], fn.segments[cur:])
784 // appending a new segment does
785 // not invalidate any ptrs
788 seg.Truncate(len(cando))
789 fn.memsize += int64(len(cando))
790 fn.segments[cur] = seg
794 // Finally we can copy bytes from cando to the current segment.
795 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
799 ptr.off += int64(len(cando))
800 ptr.segmentOff += len(cando)
801 if ptr.segmentOff >= maxBlockSize {
802 fn.pruneMemSegments()
804 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
809 fn.fileinfo.modTime = time.Now()
814 // Write some data out to disk to reduce memory use. Caller must have
816 func (fn *filenode) pruneMemSegments() {
817 // TODO: share code with (*dirnode)flush()
818 // TODO: pack/flush small blocks too, when fragmented
819 for idx, seg := range fn.segments {
820 seg, ok := seg.(*memSegment)
821 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
824 // Setting seg.flushing guarantees seg.buf will not be
825 // modified in place: WriteAt and Truncate will
826 // allocate a new buf instead, if necessary.
827 idx, buf := idx, seg.buf
828 done := make(chan struct{})
830 // If lots of background writes are already in
831 // progress, block here until one finishes, rather
832 // than pile up an unlimited number of buffered writes
833 // and network flush operations.
834 fn.fs.throttle().Acquire()
837 resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
839 Replicas: fn.fs.replicas,
840 StorageClasses: fn.fs.storageClasses,
842 fn.fs.throttle().Release()
845 if seg.flushing != done {
846 // A new seg.buf has been allocated.
850 // TODO: stall (or return errors from)
851 // subsequent writes until flushing
852 // starts to succeed.
855 if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
856 // Segment has been dropped/moved/resized.
859 fn.memsize -= int64(len(buf))
860 fn.segments[idx] = storedSegment{
862 locator: resp.Locator,
871 // Block until all pending pruneMemSegments/flush work is
872 // finished. Caller must NOT have lock.
873 func (fn *filenode) waitPrune() {
874 var pending []<-chan struct{}
876 for _, seg := range fn.segments {
877 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
878 pending = append(pending, seg.flushing)
882 for _, p := range pending {
887 func (fn *filenode) Snapshot() (inode, error) {
890 segments := make([]segment, 0, len(fn.segments))
891 for _, seg := range fn.segments {
892 segments = append(segments, seg.Slice(0, seg.Len()))
895 fileinfo: fn.fileinfo,
900 func (fn *filenode) Splice(repl inode) error {
901 repl, err := repl.Snapshot()
906 defer fn.parent.Unlock()
909 _, err = fn.parent.Child(fn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
913 switch repl := repl.(type) {
915 repl.parent = fn.parent
916 repl.fileinfo.name = fn.fileinfo.name
917 repl.setTreeFS(fn.fs)
919 repl.parent = fn.parent
920 repl.fileinfo.name = fn.fileinfo.name
923 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
928 type dirnode struct {
929 fs *collectionFileSystem
933 func (dn *dirnode) FS() FileSystem {
937 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
938 if dn == dn.fs.rootnode() && name == ".arvados#collection" {
939 gn := &getternode{Getter: func() ([]byte, error) {
942 coll.ManifestText, err = dn.fs.MarshalManifest(".")
946 coll.UUID = dn.fs.uuid
947 data, err := json.Marshal(&coll)
949 data = append(data, '\n')
953 gn.SetParent(dn, name)
956 return dn.treenode.Child(name, replace)
959 type fnSegmentRef struct {
964 // commitBlock concatenates the data from the given filenode segments
965 // (which must be *memSegments), writes the data out to Keep as a
966 // single block, and replaces the filenodes' *memSegments with
967 // storedSegments that reference the relevant portions of the new
970 // bufsize is the total data size in refs. It is used to preallocate
971 // the correct amount of memory when len(refs)>1.
973 // If sync is false, commitBlock returns right away, after starting a
974 // goroutine to do the writes, reacquire the filenodes' locks, and
975 // swap out the *memSegments. Some filenodes' segments might get
976 // modified/rearranged in the meantime, in which case commitBlock
977 // won't replace them.
979 // Caller must have write lock.
980 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
984 if err := ctx.Err(); err != nil {
987 done := make(chan struct{})
989 segs := make([]*memSegment, 0, len(refs))
990 offsets := make([]int, 0, len(refs)) // location of segment's data within block
991 for _, ref := range refs {
992 seg := ref.fn.segments[ref.idx].(*memSegment)
993 if !sync && seg.flushingUnfinished() {
994 // Let the other flushing goroutine finish. If
995 // it fails, we'll try again next time.
999 // In sync mode, we proceed regardless of
1000 // whether another flush is in progress: It
1001 // can't finish before we do, because we hold
1002 // fn's lock until we finish our own writes.
1004 offsets = append(offsets, len(block))
1007 } else if block == nil {
1008 block = append(make([]byte, 0, bufsize), seg.buf...)
1010 block = append(block, seg.buf...)
1012 segs = append(segs, seg)
1014 blocksize := len(block)
1015 dn.fs.throttle().Acquire()
1016 errs := make(chan error, 1)
1020 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
1022 Replicas: dn.fs.replicas,
1023 StorageClasses: dn.fs.storageClasses,
1025 dn.fs.throttle().Release()
1030 for idx, ref := range refs {
1033 // In async mode, fn's lock was
1034 // released while we were waiting for
1035 // PutB(); lots of things might have
1037 if len(ref.fn.segments) <= ref.idx {
1038 // file segments have
1039 // rearranged or changed in
1043 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
1044 // segment has been replaced
1047 } else if seg.flushing != done {
1048 // seg.buf has been replaced
1053 data := ref.fn.segments[ref.idx].(*memSegment).buf
1054 ref.fn.segments[ref.idx] = storedSegment{
1056 locator: resp.Locator,
1058 offset: offsets[idx],
1061 // atomic is needed here despite caller having
1062 // lock: caller might be running concurrent
1063 // commitBlock() goroutines using the same
1064 // lock, writing different segments from the
1066 atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
1078 type flushOpts struct {
1083 // flush in-memory data and remote-cluster block references (for the
1084 // children with the given names, which must be children of dn) to
1085 // local-cluster persistent storage.
1087 // Caller must have write lock on dn and the named children.
1089 // If any children are dirs, they will be flushed recursively.
1090 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
1091 cg := newContextGroup(ctx)
1094 goCommit := func(refs []fnSegmentRef, bufsize int) {
1095 cg.Go(func() error {
1096 return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
1100 var pending []fnSegmentRef
1101 var pendingLen int = 0
1102 localLocator := map[string]string{}
1103 for _, name := range names {
1104 switch node := dn.inodes[name].(type) {
1106 grandchildNames := node.sortedNames()
1107 for _, grandchildName := range grandchildNames {
1108 grandchild := node.inodes[grandchildName]
1110 defer grandchild.Unlock()
1112 cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
1114 for idx, seg := range node.segments {
1115 switch seg := seg.(type) {
1117 loc, ok := localLocator[seg.locator]
1120 loc, err = dn.fs.LocalLocator(seg.locator)
1124 localLocator[seg.locator] = loc
1127 node.segments[idx] = seg
1129 if seg.Len() > maxBlockSize/2 {
1130 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
1133 if pendingLen+seg.Len() > maxBlockSize {
1134 goCommit(pending, pendingLen)
1138 pending = append(pending, fnSegmentRef{node, idx})
1139 pendingLen += seg.Len()
1141 panic(fmt.Sprintf("can't sync segment type %T", seg))
1146 if opts.shortBlocks {
1147 goCommit(pending, pendingLen)
1152 // caller must have write lock.
1153 func (dn *dirnode) MemorySize() (size int64) {
1154 for _, name := range dn.sortedNames() {
1155 node := dn.inodes[name]
1158 switch node := node.(type) {
1160 size += node.MemorySize()
1162 for _, seg := range node.segments {
1163 switch seg := seg.(type) {
1165 size += int64(seg.Len())
1173 // caller must have write lock.
1174 func (dn *dirnode) sortedNames() []string {
1175 names := make([]string, 0, len(dn.inodes))
1176 for name := range dn.inodes {
1177 names = append(names, name)
1183 // caller must have write lock.
1184 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1185 cg := newContextGroup(ctx)
1188 if len(dn.inodes) == 0 {
1192 // Express the existence of an empty directory by
1193 // adding an empty file named `\056`, which (unlike
1194 // the more obvious spelling `.`) is accepted by the
1195 // API's manifest validator.
1196 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
1199 names := dn.sortedNames()
1201 // Wait for children to finish any pending write operations
1202 // before locking them.
1203 for _, name := range names {
1204 node := dn.inodes[name]
1205 if fn, ok := node.(*filenode); ok {
1210 var dirnames []string
1211 var filenames []string
1212 for _, name := range names {
1213 node := dn.inodes[name]
1216 switch node := node.(type) {
1218 dirnames = append(dirnames, name)
1220 filenames = append(filenames, name)
1222 panic(fmt.Sprintf("can't marshal inode type %T", node))
1226 subdirs := make([]string, len(dirnames))
1228 for i, name := range dirnames {
1230 cg.Go(func() error {
1231 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1237 cg.Go(func() error {
1239 type filepart struct {
1245 var fileparts []filepart
1247 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1250 for _, name := range filenames {
1251 node := dn.inodes[name].(*filenode)
1252 if len(node.segments) == 0 {
1253 fileparts = append(fileparts, filepart{name: name})
1256 for _, seg := range node.segments {
1257 switch seg := seg.(type) {
1259 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1260 streamLen -= int64(seg.size)
1262 blocks = append(blocks, seg.locator)
1266 offset: streamLen + int64(seg.offset),
1267 length: int64(seg.length),
1269 if prev := len(fileparts) - 1; prev >= 0 &&
1270 fileparts[prev].name == name &&
1271 fileparts[prev].offset+fileparts[prev].length == next.offset {
1272 fileparts[prev].length += next.length
1274 fileparts = append(fileparts, next)
1276 streamLen += int64(seg.size)
1278 // This can't happen: we
1279 // haven't unlocked since
1280 // calling flush(sync=true).
1281 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1285 var filetokens []string
1286 for _, s := range fileparts {
1287 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1289 if len(filetokens) == 0 {
1291 } else if len(blocks) == 0 {
1292 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1294 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1298 return rootdir + strings.Join(subdirs, ""), err
1301 func (dn *dirnode) loadManifest(txt string) error {
1302 streams := bytes.Split([]byte(txt), []byte{'\n'})
1303 if len(streams[len(streams)-1]) != 0 {
1304 return fmt.Errorf("line %d: no trailing newline", len(streams))
1306 streams = streams[:len(streams)-1]
1307 segments := []storedSegment{}
1308 // To reduce allocs, we reuse a single "pathparts" slice
1309 // (pre-split on "/" separators) for the duration of this
1311 var pathparts []string
1312 // To reduce allocs, we reuse a single "toks" slice of 3 byte
1314 var toks = make([][]byte, 3)
1315 // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1316 // into the toks slice rather than allocating a new one, and
1317 // returns the number of toks (1, 2, or 3).
1318 splitToToks := func(src []byte, c rune) int {
1319 c1 := bytes.IndexRune(src, c)
1324 toks[0], src = src[:c1], src[c1+1:]
1325 c2 := bytes.IndexRune(src, c)
1330 toks[1], toks[2] = src[:c2], src[c2+1:]
1333 for i, stream := range streams {
1335 var anyFileTokens bool
1338 segments = segments[:0]
1341 for i, token := range bytes.Split(stream, []byte{' '}) {
1343 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1344 streamparts = len(pathparts)
1347 if !bytes.ContainsRune(token, ':') {
1349 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1351 if splitToToks(token, '+') < 2 {
1352 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1354 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1355 if err != nil || length < 0 {
1356 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1358 segments = append(segments, storedSegment{
1359 locator: string(token),
1362 length: int(length),
1365 } else if len(segments) == 0 {
1366 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1368 if splitToToks(token, ':') != 3 {
1369 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1371 anyFileTokens = true
1373 offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1374 if err != nil || offset < 0 {
1375 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1377 length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1378 if err != nil || length < 0 {
1379 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1381 if !bytes.ContainsAny(toks[2], `\/`) {
1382 // optimization for a common case
1383 pathparts = append(pathparts[:streamparts], string(toks[2]))
1385 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1387 fnode, err := dn.createFileAndParents(pathparts)
1388 if fnode == nil && err == nil && length == 0 {
1389 // Special case: an empty file used as
1390 // a marker to preserve an otherwise
1391 // empty directory in a manifest.
1394 if err != nil || (fnode == nil && length != 0) {
1395 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1397 // Map the stream offset/range coordinates to
1398 // block/offset/range coordinates and add
1399 // corresponding storedSegments to the filenode
1401 // Can't continue where we left off.
1402 // TODO: binary search instead of
1403 // rewinding all the way (but this
1404 // situation might be rare anyway)
1407 for ; segIdx < len(segments); segIdx++ {
1408 seg := segments[segIdx]
1409 next := pos + int64(seg.Len())
1410 if next <= offset || seg.Len() == 0 {
1414 if pos >= offset+length {
1419 blkOff = int(offset - pos)
1421 blkLen := seg.Len() - blkOff
1422 if pos+int64(blkOff+blkLen) > offset+length {
1423 blkLen = int(offset + length - pos - int64(blkOff))
1425 fnode.appendSegment(storedSegment{
1427 locator: seg.locator,
1432 if next > offset+length {
1438 if segIdx == len(segments) && pos < offset+length {
1439 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1443 return fmt.Errorf("line %d: no file segments", lineno)
1444 } else if len(segments) == 0 {
1445 return fmt.Errorf("line %d: no locators", lineno)
1446 } else if streamparts == 0 {
1447 return fmt.Errorf("line %d: no stream name", lineno)
1453 // only safe to call from loadManifest -- no locking.
1455 // If path is a "parent directory exists" marker (the last path
1456 // component is "."), the returned values are both nil.
1458 // Newly added nodes have modtime==0. Caller is responsible for fixing
1459 // them with backdateTree.
1460 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1462 basename := names[len(names)-1]
1463 for _, name := range names[:len(names)-1] {
1469 // can't be sure parent will be a *dirnode
1470 return nil, ErrInvalidArgument
1472 node = node.Parent()
1476 unlock := node.Unlock
1477 node, err = node.Child(name, func(child inode) (inode, error) {
1479 // note modtime will be fixed later in backdateTree()
1480 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1484 child.SetParent(node, name)
1486 } else if !child.IsDir() {
1487 return child, ErrFileExists
1497 if basename == "." {
1499 } else if !permittedName(basename) {
1500 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1505 _, err = node.Child(basename, func(child inode) (inode, error) {
1506 switch child := child.(type) {
1508 child, err = node.FS().newNode(basename, 0755, time.Time{})
1512 child.SetParent(node, basename)
1513 fn = child.(*filenode)
1519 return child, ErrIsDirectory
1521 return child, ErrInvalidArgument
1527 func (dn *dirnode) TreeSize() (bytes int64) {
1530 for _, i := range dn.inodes {
1531 switch i := i.(type) {
1535 bytes += i.TreeSize()
1541 func (dn *dirnode) Snapshot() (inode, error) {
1542 return dn.snapshot()
1545 func (dn *dirnode) snapshot() (*dirnode, error) {
1550 inodes: make(map[string]inode, len(dn.inodes)),
1551 fileinfo: dn.fileinfo,
1554 for name, child := range dn.inodes {
1555 dupchild, err := child.Snapshot()
1559 snap.inodes[name] = dupchild
1560 dupchild.SetParent(snap, name)
1565 func (dn *dirnode) Splice(repl inode) error {
1566 repl, err := repl.Snapshot()
1568 return fmt.Errorf("cannot copy snapshot: %w", err)
1570 switch repl := repl.(type) {
1572 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
1576 dn.inodes = repl.inodes
1580 defer dn.parent.Unlock()
1581 removing, err := dn.parent.Child(dn.fileinfo.name, nil)
1583 return fmt.Errorf("cannot use Splice to replace a top-level directory with a file: %w", ErrInvalidOperation)
1584 } else if removing != dn {
1585 // If ../thisdirname is not this dirnode, it
1586 // must be an inode that wraps a dirnode, like
1587 // a collectionFileSystem or deferrednode.
1588 if deferred, ok := removing.(*deferrednode); ok {
1589 // More useful to report the type of
1590 // the wrapped node rather than just
1591 // *deferrednode. (We know the real
1592 // inode is already loaded because dn
1594 removing = deferred.realinode()
1596 return fmt.Errorf("cannot use Splice to attach a file at top level of %T: %w", removing, ErrInvalidOperation)
1600 _, err = dn.parent.Child(dn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
1602 return fmt.Errorf("error replacing filenode: dn.parent.Child(): %w", err)
1609 func (dn *dirnode) setTreeFS(fs *collectionFileSystem) {
1611 for _, child := range dn.inodes {
1612 switch child := child.(type) {
1621 type segment interface {
1624 // Return a new segment with a subsection of the data from this
1625 // one. length<0 means length=Len()-off.
1626 Slice(off int, length int) segment
1629 type memSegment struct {
1631 // If flushing is not nil and not ready/closed, then a) buf is
1632 // being shared by a pruneMemSegments goroutine, and must be
1633 // copied on write; and b) the flushing channel will close
1634 // when the goroutine finishes, whether it succeeds or not.
1635 flushing <-chan struct{}
1638 func (me *memSegment) flushingUnfinished() bool {
1639 if me.flushing == nil {
1651 func (me *memSegment) Len() int {
1655 func (me *memSegment) Slice(off, length int) segment {
1657 length = len(me.buf) - off
1659 buf := make([]byte, length)
1660 copy(buf, me.buf[off:])
1661 return &memSegment{buf: buf}
1664 func (me *memSegment) Truncate(n int) {
1665 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1668 newsize = newsize << 2
1670 newbuf := make([]byte, n, newsize)
1671 copy(newbuf, me.buf)
1672 me.buf, me.flushing = newbuf, nil
1674 // reclaim existing capacity, and zero reclaimed part
1675 oldlen := len(me.buf)
1677 for i := oldlen; i < n; i++ {
1683 func (me *memSegment) WriteAt(p []byte, off int) {
1684 if off+len(p) > len(me.buf) {
1685 panic("overflowed segment")
1687 if me.flushing != nil {
1688 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1690 copy(me.buf[off:], p)
1693 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1694 if off > int64(me.Len()) {
1698 n = copy(p, me.buf[int(off):])
1705 type storedSegment struct {
1708 size int // size of stored block (also encoded in locator)
1709 offset int // position of segment within the stored block
1710 length int // bytes in this segment (offset + length <= size)
1713 func (se storedSegment) Len() int {
1717 func (se storedSegment) Slice(n, size int) segment {
1720 if size >= 0 && se.length > size {
1726 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1727 if off > int64(se.length) {
1730 maxlen := se.length - int(off)
1731 if len(p) > maxlen {
1733 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1739 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1742 func canonicalName(name string) string {
1743 name = path.Clean("/" + name)
1744 if name == "/" || name == "./" {
1746 } else if strings.HasPrefix(name, "/") {
1752 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1754 func manifestUnescapeFunc(seq string) string {
1758 i, err := strconv.ParseUint(seq[1:], 8, 8)
1760 // Invalid escape sequence: can't unescape.
1763 return string([]byte{byte(i)})
1766 func manifestUnescape(s string) string {
1767 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1770 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1772 func manifestEscapeFunc(seq string) string {
1773 return fmt.Sprintf("\\%03o", byte(seq[0]))
1776 func manifestEscape(s string) string {
1777 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)