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()
1163 for _, seg := range node.segments {
1164 switch seg := seg.(type) {
1166 size += int64(seg.Len())
1175 // caller must have write lock.
1176 func (dn *dirnode) sortedNames() []string {
1177 names := make([]string, 0, len(dn.inodes))
1178 for name := range dn.inodes {
1179 names = append(names, name)
1185 // caller must have write lock.
1186 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1187 cg := newContextGroup(ctx)
1190 if len(dn.inodes) == 0 {
1194 // Express the existence of an empty directory by
1195 // adding an empty file named `\056`, which (unlike
1196 // the more obvious spelling `.`) is accepted by the
1197 // API's manifest validator.
1198 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
1201 names := dn.sortedNames()
1203 // Wait for children to finish any pending write operations
1204 // before locking them.
1205 for _, name := range names {
1206 node := dn.inodes[name]
1207 if fn, ok := node.(*filenode); ok {
1212 var dirnames []string
1213 var filenames []string
1214 for _, name := range names {
1215 node := dn.inodes[name]
1218 switch node := node.(type) {
1220 dirnames = append(dirnames, name)
1222 filenames = append(filenames, name)
1224 panic(fmt.Sprintf("can't marshal inode type %T", node))
1228 subdirs := make([]string, len(dirnames))
1230 for i, name := range dirnames {
1232 cg.Go(func() error {
1233 txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1239 cg.Go(func() error {
1241 type filepart struct {
1247 var fileparts []filepart
1249 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1252 for _, name := range filenames {
1253 node := dn.inodes[name].(*filenode)
1254 if len(node.segments) == 0 {
1255 fileparts = append(fileparts, filepart{name: name})
1258 for _, seg := range node.segments {
1259 switch seg := seg.(type) {
1261 if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1262 streamLen -= int64(seg.size)
1264 blocks = append(blocks, seg.locator)
1268 offset: streamLen + int64(seg.offset),
1269 length: int64(seg.length),
1271 if prev := len(fileparts) - 1; prev >= 0 &&
1272 fileparts[prev].name == name &&
1273 fileparts[prev].offset+fileparts[prev].length == next.offset {
1274 fileparts[prev].length += next.length
1276 fileparts = append(fileparts, next)
1278 streamLen += int64(seg.size)
1280 // This can't happen: we
1281 // haven't unlocked since
1282 // calling flush(sync=true).
1283 panic(fmt.Sprintf("can't marshal segment type %T", seg))
1287 var filetokens []string
1288 for _, s := range fileparts {
1289 filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1291 if len(filetokens) == 0 {
1293 } else if len(blocks) == 0 {
1294 blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1296 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1300 return rootdir + strings.Join(subdirs, ""), err
1303 func (dn *dirnode) loadManifest(txt string) error {
1304 streams := bytes.Split([]byte(txt), []byte{'\n'})
1305 if len(streams[len(streams)-1]) != 0 {
1306 return fmt.Errorf("line %d: no trailing newline", len(streams))
1308 streams = streams[:len(streams)-1]
1309 segments := []storedSegment{}
1310 // To reduce allocs, we reuse a single "pathparts" slice
1311 // (pre-split on "/" separators) for the duration of this
1313 var pathparts []string
1314 // To reduce allocs, we reuse a single "toks" slice of 3 byte
1316 var toks = make([][]byte, 3)
1317 // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1318 // into the toks slice rather than allocating a new one, and
1319 // returns the number of toks (1, 2, or 3).
1320 splitToToks := func(src []byte, c rune) int {
1321 c1 := bytes.IndexRune(src, c)
1326 toks[0], src = src[:c1], src[c1+1:]
1327 c2 := bytes.IndexRune(src, c)
1332 toks[1], toks[2] = src[:c2], src[c2+1:]
1335 for i, stream := range streams {
1337 var anyFileTokens bool
1340 segments = segments[:0]
1343 for i, token := range bytes.Split(stream, []byte{' '}) {
1345 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1346 streamparts = len(pathparts)
1349 if !bytes.ContainsRune(token, ':') {
1351 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1353 if splitToToks(token, '+') < 2 {
1354 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1356 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1357 if err != nil || length < 0 {
1358 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1360 segments = append(segments, storedSegment{
1361 locator: string(token),
1364 length: int(length),
1367 } else if len(segments) == 0 {
1368 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1370 if splitToToks(token, ':') != 3 {
1371 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1373 anyFileTokens = true
1375 offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1376 if err != nil || offset < 0 {
1377 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1379 length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1380 if err != nil || length < 0 {
1381 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1383 if !bytes.ContainsAny(toks[2], `\/`) {
1384 // optimization for a common case
1385 pathparts = append(pathparts[:streamparts], string(toks[2]))
1387 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1389 fnode, err := dn.createFileAndParents(pathparts)
1390 if fnode == nil && err == nil && length == 0 {
1391 // Special case: an empty file used as
1392 // a marker to preserve an otherwise
1393 // empty directory in a manifest.
1396 if err != nil || (fnode == nil && length != 0) {
1397 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1399 // Map the stream offset/range coordinates to
1400 // block/offset/range coordinates and add
1401 // corresponding storedSegments to the filenode
1403 // Can't continue where we left off.
1404 // TODO: binary search instead of
1405 // rewinding all the way (but this
1406 // situation might be rare anyway)
1409 for ; segIdx < len(segments); segIdx++ {
1410 seg := segments[segIdx]
1411 next := pos + int64(seg.Len())
1412 if next <= offset || seg.Len() == 0 {
1416 if pos >= offset+length {
1421 blkOff = int(offset - pos)
1423 blkLen := seg.Len() - blkOff
1424 if pos+int64(blkOff+blkLen) > offset+length {
1425 blkLen = int(offset + length - pos - int64(blkOff))
1427 fnode.appendSegment(storedSegment{
1429 locator: seg.locator,
1434 if next > offset+length {
1440 if segIdx == len(segments) && pos < offset+length {
1441 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1445 return fmt.Errorf("line %d: no file segments", lineno)
1446 } else if len(segments) == 0 {
1447 return fmt.Errorf("line %d: no locators", lineno)
1448 } else if streamparts == 0 {
1449 return fmt.Errorf("line %d: no stream name", lineno)
1455 // only safe to call from loadManifest -- no locking.
1457 // If path is a "parent directory exists" marker (the last path
1458 // component is "."), the returned values are both nil.
1460 // Newly added nodes have modtime==0. Caller is responsible for fixing
1461 // them with backdateTree.
1462 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1464 basename := names[len(names)-1]
1465 for _, name := range names[:len(names)-1] {
1471 // can't be sure parent will be a *dirnode
1472 return nil, ErrInvalidArgument
1474 node = node.Parent()
1478 unlock := node.Unlock
1479 node, err = node.Child(name, func(child inode) (inode, error) {
1481 // note modtime will be fixed later in backdateTree()
1482 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1486 child.SetParent(node, name)
1488 } else if !child.IsDir() {
1489 return child, ErrFileExists
1499 if basename == "." {
1501 } else if !permittedName(basename) {
1502 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1507 _, err = node.Child(basename, func(child inode) (inode, error) {
1508 switch child := child.(type) {
1510 child, err = node.FS().newNode(basename, 0755, time.Time{})
1514 child.SetParent(node, basename)
1515 fn = child.(*filenode)
1521 return child, ErrIsDirectory
1523 return child, ErrInvalidArgument
1529 func (dn *dirnode) TreeSize() (bytes int64) {
1532 for _, i := range dn.inodes {
1533 switch i := i.(type) {
1537 bytes += i.TreeSize()
1543 func (dn *dirnode) Snapshot() (inode, error) {
1544 return dn.snapshot()
1547 func (dn *dirnode) snapshot() (*dirnode, error) {
1552 inodes: make(map[string]inode, len(dn.inodes)),
1553 fileinfo: dn.fileinfo,
1556 for name, child := range dn.inodes {
1557 dupchild, err := child.Snapshot()
1561 snap.inodes[name] = dupchild
1562 dupchild.SetParent(snap, name)
1567 func (dn *dirnode) Splice(repl inode) error {
1568 repl, err := repl.Snapshot()
1570 return fmt.Errorf("cannot copy snapshot: %w", err)
1572 switch repl := repl.(type) {
1574 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
1578 dn.inodes = repl.inodes
1582 defer dn.parent.Unlock()
1583 removing, err := dn.parent.Child(dn.fileinfo.name, nil)
1585 return fmt.Errorf("cannot use Splice to replace a top-level directory with a file: %w", ErrInvalidOperation)
1586 } else if removing != dn {
1587 // If ../thisdirname is not this dirnode, it
1588 // must be an inode that wraps a dirnode, like
1589 // a collectionFileSystem or deferrednode.
1590 if deferred, ok := removing.(*deferrednode); ok {
1591 // More useful to report the type of
1592 // the wrapped node rather than just
1593 // *deferrednode. (We know the real
1594 // inode is already loaded because dn
1596 removing = deferred.realinode()
1598 return fmt.Errorf("cannot use Splice to attach a file at top level of %T: %w", removing, ErrInvalidOperation)
1602 _, err = dn.parent.Child(dn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
1604 return fmt.Errorf("error replacing filenode: dn.parent.Child(): %w", err)
1611 func (dn *dirnode) setTreeFS(fs *collectionFileSystem) {
1613 for _, child := range dn.inodes {
1614 switch child := child.(type) {
1623 type segment interface {
1626 // Return a new segment with a subsection of the data from this
1627 // one. length<0 means length=Len()-off.
1628 Slice(off int, length int) segment
1631 type memSegment struct {
1633 // If flushing is not nil and not ready/closed, then a) buf is
1634 // being shared by a pruneMemSegments goroutine, and must be
1635 // copied on write; and b) the flushing channel will close
1636 // when the goroutine finishes, whether it succeeds or not.
1637 flushing <-chan struct{}
1640 func (me *memSegment) flushingUnfinished() bool {
1641 if me.flushing == nil {
1653 func (me *memSegment) Len() int {
1657 func (me *memSegment) Slice(off, length int) segment {
1659 length = len(me.buf) - off
1661 buf := make([]byte, length)
1662 copy(buf, me.buf[off:])
1663 return &memSegment{buf: buf}
1666 func (me *memSegment) Truncate(n int) {
1667 if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1670 newsize = newsize << 2
1672 newbuf := make([]byte, n, newsize)
1673 copy(newbuf, me.buf)
1674 me.buf, me.flushing = newbuf, nil
1676 // reclaim existing capacity, and zero reclaimed part
1677 oldlen := len(me.buf)
1679 for i := oldlen; i < n; i++ {
1685 func (me *memSegment) WriteAt(p []byte, off int) {
1686 if off+len(p) > len(me.buf) {
1687 panic("overflowed segment")
1689 if me.flushing != nil {
1690 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1692 copy(me.buf[off:], p)
1695 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1696 if off > int64(me.Len()) {
1700 n = copy(p, me.buf[int(off):])
1707 type storedSegment struct {
1710 size int // size of stored block (also encoded in locator)
1711 offset int // position of segment within the stored block
1712 length int // bytes in this segment (offset + length <= size)
1715 func (se storedSegment) Len() int {
1719 func (se storedSegment) Slice(n, size int) segment {
1722 if size >= 0 && se.length > size {
1728 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1729 if off > int64(se.length) {
1732 maxlen := se.length - int(off)
1733 if len(p) > maxlen {
1735 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1741 return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1744 func canonicalName(name string) string {
1745 name = path.Clean("/" + name)
1746 if name == "/" || name == "./" {
1748 } else if strings.HasPrefix(name, "/") {
1754 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1756 func manifestUnescapeFunc(seq string) string {
1760 i, err := strconv.ParseUint(seq[1:], 8, 8)
1762 // Invalid escape sequence: can't unescape.
1765 return string([]byte{byte(i)})
1768 func manifestUnescape(s string) string {
1769 return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1772 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1774 func manifestEscapeFunc(seq string) string {
1775 return fmt.Sprintf("\\%03o", byte(seq[0]))
1778 func manifestEscape(s string) string {
1779 return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)