ccfbdc4da262c13ee3d319ad072f73a10b9b1d0a
[arvados.git] / sdk / go / arvados / fs_collection.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "context"
10         "encoding/json"
11         "fmt"
12         "io"
13         "os"
14         "path"
15         "regexp"
16         "sort"
17         "strconv"
18         "strings"
19         "sync"
20         "sync/atomic"
21         "time"
22 )
23
24 var (
25         maxBlockSize      = 1 << 26
26         concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
27 )
28
29 // A CollectionFileSystem is a FileSystem that can be serialized as a
30 // manifest and stored as a collection.
31 type CollectionFileSystem interface {
32         FileSystem
33
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)
39
40         // Total data bytes in all files.
41         Size() int64
42 }
43
44 type collectionFileSystem struct {
45         fileSystem
46         uuid           string
47         savedPDH       atomic.Value
48         replicas       int
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.
54         //
55         // When the guessed TTL is much smaller than the real TTL,
56         // preemptive signature refresh is delayed or missed entirely,
57         // which is OK.
58         guessSignatureTTL time.Duration
59         holdCheckChanges  time.Time
60         lockCheckChanges  sync.Mutex
61 }
62
63 // FileSystem returns a CollectionFileSystem for the collection.
64 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
65         modTime := c.ModifiedAt
66         if modTime.IsZero() {
67                 modTime = time.Now()
68         }
69         fs := &collectionFileSystem{
70                 uuid:           c.UUID,
71                 storageClasses: c.StorageClassesDesired,
72                 fileSystem: fileSystem{
73                         fsBackend: keepBackend{apiClient: client, keepClient: kc},
74                         thr:       newThrottle(concurrentWriters),
75                 },
76         }
77         fs.savedPDH.Store(c.PortableDataHash)
78         if r := c.ReplicationDesired; r != nil {
79                 fs.replicas = *r
80         }
81         root := &dirnode{
82                 fs: fs,
83                 treenode: treenode{
84                         fileinfo: fileinfo{
85                                 name:    ".",
86                                 mode:    os.ModeDir | 0755,
87                                 modTime: modTime,
88                         },
89                         inodes: make(map[string]inode),
90                 },
91         }
92         root.SetParent(root, ".")
93         if err := root.loadManifest(c.ManifestText); err != nil {
94                 return nil, err
95         }
96         backdateTree(root, modTime)
97         fs.root = root
98         return fs, nil
99 }
100
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) {
104         case *filenode:
105                 if ffunc != nil {
106                         ffunc(n)
107                 }
108         case *dirnode:
109                 if dfunc != nil {
110                         dfunc(n)
111                 }
112                 for _, n := range n.inodes {
113                         eachNode(n, ffunc, dfunc)
114                 }
115         }
116 }
117
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
124         })
125 }
126
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) {
130         var (
131                 now      = time.Now()
132                 earliest = now.Add(time.Hour * 24 * 7 * 365)
133                 latest   time.Time
134         )
135         fs.fileSystem.root.RLock()
136         eachNode(fs.root, func(fn *filenode) {
137                 fn.Lock()
138                 defer fn.Unlock()
139                 for _, seg := range fn.segments {
140                         seg, ok := seg.(storedSegment)
141                         if !ok {
142                                 continue
143                         }
144                         expiryTime, err := signatureExpiryTime(seg.locator)
145                         if err != nil {
146                                 continue
147                         }
148                         if expiryTime.Before(earliest) {
149                                 earliest = expiryTime
150                         }
151                         if expiryTime.After(latest) {
152                                 latest = expiryTime
153                         }
154                 }
155         }, nil)
156         fs.fileSystem.root.RUnlock()
157
158         if latest.IsZero() {
159                 // No signatures == 100% of TTL remaining.
160                 return 1, 1
161         }
162
163         ttl := latest.Sub(now)
164         fs.fileSystem.root.Lock()
165         {
166                 if ttl > fs.guessSignatureTTL {
167                         // ttl is closer to the real TTL than
168                         // guessSignatureTTL.
169                         fs.guessSignatureTTL = ttl
170                 } else {
171                         // Use the previous best guess to compute the
172                         // portion remaining (below, after unlocking
173                         // mutex).
174                         ttl = fs.guessSignatureTTL
175                 }
176         }
177         fs.fileSystem.root.Unlock()
178
179         return earliest.Sub(now).Seconds() / ttl.Seconds(), ttl
180 }
181
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
187                 }
188         }
189         fs.fileSystem.root.Lock()
190         defer fs.fileSystem.root.Unlock()
191         eachNode(fs.root, func(fn *filenode) {
192                 fn.Lock()
193                 defer fn.Unlock()
194                 for idx, seg := range fn.segments {
195                         seg, ok := seg.(storedSegment)
196                         if !ok {
197                                 continue
198                         }
199                         loc, ok := newLoc[stripAllHints(seg.locator)]
200                         if !ok {
201                                 continue
202                         }
203                         seg.locator = loc
204                         fn.segments[idx] = seg
205                 }
206         }, nil)
207 }
208
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
212         }
213         if perm.IsDir() {
214                 return &dirnode{
215                         fs: fs,
216                         treenode: treenode{
217                                 fileinfo: fileinfo{
218                                         name:    name,
219                                         mode:    perm | os.ModeDir,
220                                         modTime: modTime,
221                                 },
222                                 inodes: make(map[string]inode),
223                         },
224                 }, nil
225         }
226         return &filenode{
227                 fs: fs,
228                 fileinfo: fileinfo{
229                         name:    name,
230                         mode:    perm & ^os.ModeDir,
231                         modTime: modTime,
232                 },
233         }, nil
234 }
235
236 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
237         return fs.rootnode().Child(name, replace)
238 }
239
240 func (fs *collectionFileSystem) FS() FileSystem {
241         return fs
242 }
243
244 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
245         return fs.rootnode().FileInfo()
246 }
247
248 func (fs *collectionFileSystem) IsDir() bool {
249         return true
250 }
251
252 func (fs *collectionFileSystem) Lock() {
253         fs.rootnode().Lock()
254 }
255
256 func (fs *collectionFileSystem) Unlock() {
257         fs.rootnode().Unlock()
258 }
259
260 func (fs *collectionFileSystem) RLock() {
261         fs.rootnode().RLock()
262 }
263
264 func (fs *collectionFileSystem) RUnlock() {
265         fs.rootnode().RUnlock()
266 }
267
268 func (fs *collectionFileSystem) Parent() inode {
269         return fs.rootnode().Parent()
270 }
271
272 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
273         return 0, ptr, ErrInvalidOperation
274 }
275
276 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
277         return 0, ptr, ErrInvalidOperation
278 }
279
280 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
281         return fs.rootnode().Readdir()
282 }
283
284 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
285         fs.rootnode().SetParent(parent, name)
286 }
287
288 func (fs *collectionFileSystem) Truncate(int64) error {
289         return ErrInvalidOperation
290 }
291
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() == "" {
296                 return nil
297         }
298
299         // First try UUID if any, then last known PDH. Stop if all
300         // signatures are new enough.
301         checkingAll := false
302         for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
303                 if id == "" {
304                         continue
305                 }
306
307                 fs.lockCheckChanges.Lock()
308                 if !checkingAll && fs.holdCheckChanges.After(time.Now()) {
309                         fs.lockCheckChanges.Unlock()
310                         return nil
311                 }
312                 remain, ttl := fs.signatureTimeLeft()
313                 if remain > 0.01 && !checkingAll {
314                         fs.holdCheckChanges = time.Now().Add(ttl / 100)
315                 }
316                 fs.lockCheckChanges.Unlock()
317
318                 if remain >= 0.5 {
319                         break
320                 }
321                 checkingAll = true
322                 var coll Collection
323                 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
324                 if err != nil {
325                         continue
326                 }
327                 fs.updateSignatures(coll.ManifestText)
328         }
329         return nil
330 }
331
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()
342                 return locator
343         }
344         var manifests string
345         for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
346                 if id == "" {
347                         continue
348                 }
349                 var coll Collection
350                 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
351                 if err != nil {
352                         continue
353                 }
354                 manifests += coll.ManifestText
355         }
356         hash := stripAllHints(locator)
357         for _, tok := range regexp.MustCompile(`\S+`).FindAllString(manifests, -1) {
358                 if mBlkRe.MatchString(tok) {
359                         if stripAllHints(tok) == hash {
360                                 locator = tok
361                                 break
362                         }
363                 }
364         }
365         go fs.updateSignatures(manifests)
366         return locator
367 }
368
369 func (fs *collectionFileSystem) Sync() error {
370         err := fs.checkChangesOnServer()
371         if err != nil {
372                 return err
373         }
374         if fs.uuid == "" {
375                 return nil
376         }
377         txt, err := fs.MarshalManifest(".")
378         if err != nil {
379                 return fmt.Errorf("sync failed: %s", err)
380         }
381         if PortableDataHash(txt) == fs.savedPDH.Load() {
382                 // No local changes since last save or initial load.
383                 return nil
384         }
385         coll := Collection{
386                 UUID:         fs.uuid,
387                 ManifestText: txt,
388         }
389
390         selectFields := []string{"uuid", "portable_data_hash"}
391         fs.lockCheckChanges.Lock()
392         remain, _ := fs.signatureTimeLeft()
393         fs.lockCheckChanges.Unlock()
394         if remain < 0.5 {
395                 selectFields = append(selectFields, "manifest_text")
396         }
397
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,
401                 },
402                 "select": selectFields,
403         })
404         if err != nil {
405                 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
406         }
407         fs.updateSignatures(coll.ManifestText)
408         fs.savedPDH.Store(coll.PortableDataHash)
409         return nil
410 }
411
412 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
413         node, err := rlookup(fs.fileSystem.root, path)
414         if err != nil {
415                 return err
416         }
417         dn, ok := node.(*dirnode)
418         if !ok {
419                 return ErrNotADirectory
420         }
421         dn.Lock()
422         defer dn.Unlock()
423         names := dn.sortedNames()
424         if path != "" {
425                 // Caller only wants to flush the specified dir,
426                 // non-recursively.  Drop subdirs from the list of
427                 // names.
428                 var filenames []string
429                 for _, name := range names {
430                         if _, ok := dn.inodes[name].(*filenode); ok {
431                                 filenames = append(filenames, name)
432                         }
433                 }
434                 names = filenames
435         }
436         for _, name := range names {
437                 child := dn.inodes[name]
438                 child.Lock()
439                 defer child.Unlock()
440         }
441         return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
442 }
443
444 func (fs *collectionFileSystem) MemorySize() int64 {
445         fs.fileSystem.root.Lock()
446         defer fs.fileSystem.root.Unlock()
447         return fs.fileSystem.root.(*dirnode).MemorySize()
448 }
449
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)
454 }
455
456 func (fs *collectionFileSystem) Size() int64 {
457         return fs.fileSystem.root.(*dirnode).TreeSize()
458 }
459
460 func (fs *collectionFileSystem) Snapshot() (inode, error) {
461         return fs.fileSystem.root.Snapshot()
462 }
463
464 func (fs *collectionFileSystem) Splice(r inode) error {
465         return fs.fileSystem.root.Splice(r)
466 }
467
468 // filenodePtr is an offset into a file that is (usually) efficient to
469 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
470 // then
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 {
476         off        int64
477         segmentIdx int
478         segmentOff int
479         repacked   int64
480 }
481
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
484 // fn.Lock().
485 //
486 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
487 // EOF.
488 //
489 // After seeking:
490 //
491 //     ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
492 //     ||
493 //     filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
494 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
495         ptr = startPtr
496         if ptr.off < 0 {
497                 // meaningless anyway
498                 return
499         } else if ptr.off >= fn.fileinfo.size {
500                 ptr.segmentIdx = len(fn.segments)
501                 ptr.segmentOff = 0
502                 ptr.repacked = fn.repacked
503                 return
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
507                 // segment
508                 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
509                         ptr.segmentIdx++
510                         ptr.segmentOff = 0
511                 }
512                 return
513         }
514         defer func() {
515                 ptr.repacked = fn.repacked
516         }()
517         if ptr.off >= fn.fileinfo.size {
518                 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
519                 return
520         }
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.
524         var off int64
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
530                 // accurate.
531                 segLen := int64(fn.segments[ptr.segmentIdx].Len())
532                 if off+segLen > ptr.off {
533                         ptr.segmentOff = int(ptr.off - off)
534                         break
535                 }
536                 off += segLen
537         }
538         return
539 }
540
541 // filenode implements inode.
542 type filenode struct {
543         parent   inode
544         fs       *collectionFileSystem
545         fileinfo fileinfo
546         segments []segment
547         // number of times `segments` has changed in a
548         // way that might invalidate a filenodePtr
549         repacked int64
550         memsize  int64 // bytes in memSegments
551         sync.RWMutex
552         nullnode
553 }
554
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())
559 }
560
561 func (fn *filenode) SetParent(p inode, name string) {
562         fn.Lock()
563         defer fn.Unlock()
564         fn.parent = p
565         fn.fileinfo.name = name
566 }
567
568 func (fn *filenode) Parent() inode {
569         fn.RLock()
570         defer fn.RUnlock()
571         return fn.parent
572 }
573
574 func (fn *filenode) FS() FileSystem {
575         return fn.fs
576 }
577
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
580 // RLock or Lock.
581 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
582         ptr = fn.seek(startPtr)
583         if ptr.off < 0 {
584                 err = ErrNegativeOffset
585                 return
586         }
587         if ptr.segmentIdx >= len(fn.segments) {
588                 err = io.EOF
589                 return
590         }
591         if ss, ok := fn.segments[ptr.segmentIdx].(storedSegment); ok {
592                 ss.locator = fn.fs.refreshSignature(ss.locator)
593                 fn.segments[ptr.segmentIdx] = ss
594         }
595         n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
596         if n > 0 {
597                 ptr.off += int64(n)
598                 ptr.segmentOff += n
599                 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
600                         ptr.segmentIdx++
601                         ptr.segmentOff = 0
602                         if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
603                                 err = nil
604                         }
605                 }
606         }
607         return
608 }
609
610 func (fn *filenode) Size() int64 {
611         fn.RLock()
612         defer fn.RUnlock()
613         return fn.fileinfo.Size()
614 }
615
616 func (fn *filenode) FileInfo() os.FileInfo {
617         fn.RLock()
618         defer fn.RUnlock()
619         return fn.fileinfo
620 }
621
622 func (fn *filenode) Truncate(size int64) error {
623         fn.Lock()
624         defer fn.Unlock()
625         return fn.truncate(size)
626 }
627
628 func (fn *filenode) truncate(size int64) error {
629         if size == fn.fileinfo.size {
630                 return nil
631         }
632         fn.repacked++
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())
638                         }
639                 }
640                 if ptr.segmentOff == 0 {
641                         fn.segments = fn.segments[:ptr.segmentIdx]
642                 } else {
643                         fn.segments = fn.segments[:ptr.segmentIdx+1]
644                         switch seg := fn.segments[ptr.segmentIdx].(type) {
645                         case *memSegment:
646                                 seg.Truncate(ptr.segmentOff)
647                                 fn.memsize += int64(seg.Len())
648                         default:
649                                 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
650                         }
651                 }
652                 fn.fileinfo.size = size
653                 return nil
654         }
655         for size > fn.fileinfo.size {
656                 grow := size - fn.fileinfo.size
657                 var seg *memSegment
658                 var ok bool
659                 if len(fn.segments) == 0 {
660                         seg = &memSegment{}
661                         fn.segments = append(fn.segments, seg)
662                 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
663                         seg = &memSegment{}
664                         fn.segments = append(fn.segments, seg)
665                 }
666                 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
667                         grow = maxgrow
668                 }
669                 seg.Truncate(seg.Len() + int(grow))
670                 fn.fileinfo.size += grow
671                 fn.memsize += grow
672         }
673         return nil
674 }
675
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
682                 }
683         }
684         ptr = fn.seek(startPtr)
685         if ptr.off < 0 {
686                 err = ErrNegativeOffset
687                 return
688         }
689         for len(p) > 0 && err == nil {
690                 cando := p
691                 if len(cando) > maxBlockSize {
692                         cando = cando[:maxBlockSize]
693                 }
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
697                 // ptr.segmentOff.
698                 cur := ptr.segmentIdx
699                 prev := ptr.segmentIdx - 1
700                 var curWritable bool
701                 if cur < len(fn.segments) {
702                         _, curWritable = fn.segments[cur].(*memSegment)
703                 }
704                 var prevAppendable bool
705                 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
706                         _, prevAppendable = fn.segments[prev].(*memSegment)
707                 }
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
712                                 // segment after it.
713                                 cando = cando[:max]
714                                 fn.segments = append(fn.segments, nil)
715                                 copy(fn.segments[cur+1:], fn.segments[cur:])
716                         } else {
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)
724                         }
725                         cur++
726                         prev++
727                         seg := &memSegment{}
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)
732                         ptr.segmentIdx++
733                         ptr.segmentOff = 0
734                         fn.repacked++
735                         ptr.repacked++
736                 } else if curWritable {
737                         if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
738                                 cando = cando[:fit]
739                         }
740                 } else {
741                         if prevAppendable {
742                                 // Shrink cando if needed to fit in
743                                 // prev segment.
744                                 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
745                                         cando = cando[:cangrow]
746                                 }
747                         }
748
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).
759                                 cando = cando[:el]
760                                 copy(fn.segments[cur:], fn.segments[cur+1:])
761                                 fn.segments = fn.segments[:len(fn.segments)-1]
762                         } else {
763                                 // shrink cur by the same #bytes we're growing prev
764                                 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
765                         }
766
767                         if prevAppendable {
768                                 // Grow prev.
769                                 ptr.segmentIdx--
770                                 ptr.segmentOff = fn.segments[prev].Len()
771                                 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
772                                 fn.memsize += int64(len(cando))
773                                 ptr.repacked++
774                                 fn.repacked++
775                         } else {
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:])
781                                         ptr.repacked++
782                                         fn.repacked++
783                                 } else {
784                                         // appending a new segment does
785                                         // not invalidate any ptrs
786                                 }
787                                 seg := &memSegment{}
788                                 seg.Truncate(len(cando))
789                                 fn.memsize += int64(len(cando))
790                                 fn.segments[cur] = seg
791                         }
792                 }
793
794                 // Finally we can copy bytes from cando to the current segment.
795                 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
796                 n += len(cando)
797                 p = p[len(cando):]
798
799                 ptr.off += int64(len(cando))
800                 ptr.segmentOff += len(cando)
801                 if ptr.segmentOff >= maxBlockSize {
802                         fn.pruneMemSegments()
803                 }
804                 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
805                         ptr.segmentOff = 0
806                         ptr.segmentIdx++
807                 }
808
809                 fn.fileinfo.modTime = time.Now()
810         }
811         return
812 }
813
814 // Write some data out to disk to reduce memory use. Caller must have
815 // write lock.
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 {
822                         continue
823                 }
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{})
829                 seg.flushing = done
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()
835                 go func() {
836                         defer close(done)
837                         resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
838                                 Data:           buf,
839                                 Replicas:       fn.fs.replicas,
840                                 StorageClasses: fn.fs.storageClasses,
841                         })
842                         fn.fs.throttle().Release()
843                         fn.Lock()
844                         defer fn.Unlock()
845                         if seg.flushing != done {
846                                 // A new seg.buf has been allocated.
847                                 return
848                         }
849                         if err != nil {
850                                 // TODO: stall (or return errors from)
851                                 // subsequent writes until flushing
852                                 // starts to succeed.
853                                 return
854                         }
855                         if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
856                                 // Segment has been dropped/moved/resized.
857                                 return
858                         }
859                         fn.memsize -= int64(len(buf))
860                         fn.segments[idx] = storedSegment{
861                                 kc:      fn.FS(),
862                                 locator: resp.Locator,
863                                 size:    len(buf),
864                                 offset:  0,
865                                 length:  len(buf),
866                         }
867                 }()
868         }
869 }
870
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{}
875         fn.Lock()
876         for _, seg := range fn.segments {
877                 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
878                         pending = append(pending, seg.flushing)
879                 }
880         }
881         fn.Unlock()
882         for _, p := range pending {
883                 <-p
884         }
885 }
886
887 func (fn *filenode) Snapshot() (inode, error) {
888         fn.RLock()
889         defer fn.RUnlock()
890         segments := make([]segment, 0, len(fn.segments))
891         for _, seg := range fn.segments {
892                 segments = append(segments, seg.Slice(0, seg.Len()))
893         }
894         return &filenode{
895                 fileinfo: fn.fileinfo,
896                 segments: segments,
897         }, nil
898 }
899
900 func (fn *filenode) Splice(repl inode) error {
901         repl, err := repl.Snapshot()
902         if err != nil {
903                 return err
904         }
905         fn.parent.Lock()
906         defer fn.parent.Unlock()
907         fn.Lock()
908         defer fn.Unlock()
909         _, err = fn.parent.Child(fn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
910         if err != nil {
911                 return err
912         }
913         switch repl := repl.(type) {
914         case *dirnode:
915                 repl.parent = fn.parent
916                 repl.fileinfo.name = fn.fileinfo.name
917                 repl.setTreeFS(fn.fs)
918         case *filenode:
919                 repl.parent = fn.parent
920                 repl.fileinfo.name = fn.fileinfo.name
921                 repl.fs = fn.fs
922         default:
923                 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
924         }
925         return nil
926 }
927
928 type dirnode struct {
929         fs *collectionFileSystem
930         treenode
931 }
932
933 func (dn *dirnode) FS() FileSystem {
934         return dn.fs
935 }
936
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) {
940                         var coll Collection
941                         var err error
942                         coll.ManifestText, err = dn.fs.MarshalManifest(".")
943                         if err != nil {
944                                 return nil, err
945                         }
946                         coll.UUID = dn.fs.uuid
947                         data, err := json.Marshal(&coll)
948                         if err == nil {
949                                 data = append(data, '\n')
950                         }
951                         return data, err
952                 }}
953                 gn.SetParent(dn, name)
954                 return gn, nil
955         }
956         return dn.treenode.Child(name, replace)
957 }
958
959 type fnSegmentRef struct {
960         fn  *filenode
961         idx int
962 }
963
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
968 // block.
969 //
970 // bufsize is the total data size in refs. It is used to preallocate
971 // the correct amount of memory when len(refs)>1.
972 //
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.
978 //
979 // Caller must have write lock.
980 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
981         if len(refs) == 0 {
982                 return nil
983         }
984         if err := ctx.Err(); err != nil {
985                 return err
986         }
987         done := make(chan struct{})
988         var block []byte
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.
996                         close(done)
997                         return nil
998                 }
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.
1003                 seg.flushing = done
1004                 offsets = append(offsets, len(block))
1005                 if len(refs) == 1 {
1006                         block = seg.buf
1007                 } else if block == nil {
1008                         block = append(make([]byte, 0, bufsize), seg.buf...)
1009                 } else {
1010                         block = append(block, seg.buf...)
1011                 }
1012                 segs = append(segs, seg)
1013         }
1014         blocksize := len(block)
1015         dn.fs.throttle().Acquire()
1016         errs := make(chan error, 1)
1017         go func() {
1018                 defer close(done)
1019                 defer close(errs)
1020                 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
1021                         Data:           block,
1022                         Replicas:       dn.fs.replicas,
1023                         StorageClasses: dn.fs.storageClasses,
1024                 })
1025                 dn.fs.throttle().Release()
1026                 if err != nil {
1027                         errs <- err
1028                         return
1029                 }
1030                 for idx, ref := range refs {
1031                         if !sync {
1032                                 ref.fn.Lock()
1033                                 // In async mode, fn's lock was
1034                                 // released while we were waiting for
1035                                 // PutB(); lots of things might have
1036                                 // changed.
1037                                 if len(ref.fn.segments) <= ref.idx {
1038                                         // file segments have
1039                                         // rearranged or changed in
1040                                         // some way
1041                                         ref.fn.Unlock()
1042                                         continue
1043                                 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
1044                                         // segment has been replaced
1045                                         ref.fn.Unlock()
1046                                         continue
1047                                 } else if seg.flushing != done {
1048                                         // seg.buf has been replaced
1049                                         ref.fn.Unlock()
1050                                         continue
1051                                 }
1052                         }
1053                         data := ref.fn.segments[ref.idx].(*memSegment).buf
1054                         ref.fn.segments[ref.idx] = storedSegment{
1055                                 kc:      dn.fs,
1056                                 locator: resp.Locator,
1057                                 size:    blocksize,
1058                                 offset:  offsets[idx],
1059                                 length:  len(data),
1060                         }
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
1065                         // same file.
1066                         atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
1067                         if !sync {
1068                                 ref.fn.Unlock()
1069                         }
1070                 }
1071         }()
1072         if sync {
1073                 return <-errs
1074         }
1075         return nil
1076 }
1077
1078 type flushOpts struct {
1079         sync        bool
1080         shortBlocks bool
1081 }
1082
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.
1086 //
1087 // Caller must have write lock on dn and the named children.
1088 //
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)
1092         defer cg.Cancel()
1093
1094         goCommit := func(refs []fnSegmentRef, bufsize int) {
1095                 cg.Go(func() error {
1096                         return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
1097                 })
1098         }
1099
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) {
1105                 case *dirnode:
1106                         grandchildNames := node.sortedNames()
1107                         for _, grandchildName := range grandchildNames {
1108                                 grandchild := node.inodes[grandchildName]
1109                                 grandchild.Lock()
1110                                 defer grandchild.Unlock()
1111                         }
1112                         cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
1113                 case *filenode:
1114                         for idx, seg := range node.segments {
1115                                 switch seg := seg.(type) {
1116                                 case storedSegment:
1117                                         loc, ok := localLocator[seg.locator]
1118                                         if !ok {
1119                                                 var err error
1120                                                 loc, err = dn.fs.LocalLocator(seg.locator)
1121                                                 if err != nil {
1122                                                         return err
1123                                                 }
1124                                                 localLocator[seg.locator] = loc
1125                                         }
1126                                         seg.locator = loc
1127                                         node.segments[idx] = seg
1128                                 case *memSegment:
1129                                         if seg.Len() > maxBlockSize/2 {
1130                                                 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
1131                                                 continue
1132                                         }
1133                                         if pendingLen+seg.Len() > maxBlockSize {
1134                                                 goCommit(pending, pendingLen)
1135                                                 pending = nil
1136                                                 pendingLen = 0
1137                                         }
1138                                         pending = append(pending, fnSegmentRef{node, idx})
1139                                         pendingLen += seg.Len()
1140                                 default:
1141                                         panic(fmt.Sprintf("can't sync segment type %T", seg))
1142                                 }
1143                         }
1144                 }
1145         }
1146         if opts.shortBlocks {
1147                 goCommit(pending, pendingLen)
1148         }
1149         return cg.Wait()
1150 }
1151
1152 // caller must have write lock.
1153 func (dn *dirnode) MemorySize() (size int64) {
1154         for _, name := range dn.sortedNames() {
1155                 node := dn.inodes[name]
1156                 node.Lock()
1157                 defer node.Unlock()
1158                 switch node := node.(type) {
1159                 case *dirnode:
1160                         size += node.MemorySize()
1161                 case *filenode:
1162                         size += 64
1163                         for _, seg := range node.segments {
1164                                 switch seg := seg.(type) {
1165                                 case *memSegment:
1166                                         size += int64(seg.Len())
1167                                 }
1168                                 size += 64
1169                         }
1170                 }
1171         }
1172         return 64 + size
1173 }
1174
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)
1180         }
1181         sort.Strings(names)
1182         return names
1183 }
1184
1185 // caller must have write lock.
1186 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1187         cg := newContextGroup(ctx)
1188         defer cg.Cancel()
1189
1190         if len(dn.inodes) == 0 {
1191                 if prefix == "." {
1192                         return "", nil
1193                 }
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
1199         }
1200
1201         names := dn.sortedNames()
1202
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 {
1208                         fn.waitPrune()
1209                 }
1210         }
1211
1212         var dirnames []string
1213         var filenames []string
1214         for _, name := range names {
1215                 node := dn.inodes[name]
1216                 node.Lock()
1217                 defer node.Unlock()
1218                 switch node := node.(type) {
1219                 case *dirnode:
1220                         dirnames = append(dirnames, name)
1221                 case *filenode:
1222                         filenames = append(filenames, name)
1223                 default:
1224                         panic(fmt.Sprintf("can't marshal inode type %T", node))
1225                 }
1226         }
1227
1228         subdirs := make([]string, len(dirnames))
1229         rootdir := ""
1230         for i, name := range dirnames {
1231                 i, name := i, name
1232                 cg.Go(func() error {
1233                         txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1234                         subdirs[i] = txt
1235                         return err
1236                 })
1237         }
1238
1239         cg.Go(func() error {
1240                 var streamLen int64
1241                 type filepart struct {
1242                         name   string
1243                         offset int64
1244                         length int64
1245                 }
1246
1247                 var fileparts []filepart
1248                 var blocks []string
1249                 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1250                         return err
1251                 }
1252                 for _, name := range filenames {
1253                         node := dn.inodes[name].(*filenode)
1254                         if len(node.segments) == 0 {
1255                                 fileparts = append(fileparts, filepart{name: name})
1256                                 continue
1257                         }
1258                         for _, seg := range node.segments {
1259                                 switch seg := seg.(type) {
1260                                 case storedSegment:
1261                                         if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1262                                                 streamLen -= int64(seg.size)
1263                                         } else {
1264                                                 blocks = append(blocks, seg.locator)
1265                                         }
1266                                         next := filepart{
1267                                                 name:   name,
1268                                                 offset: streamLen + int64(seg.offset),
1269                                                 length: int64(seg.length),
1270                                         }
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
1275                                         } else {
1276                                                 fileparts = append(fileparts, next)
1277                                         }
1278                                         streamLen += int64(seg.size)
1279                                 default:
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))
1284                                 }
1285                         }
1286                 }
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)))
1290                 }
1291                 if len(filetokens) == 0 {
1292                         return nil
1293                 } else if len(blocks) == 0 {
1294                         blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1295                 }
1296                 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1297                 return nil
1298         })
1299         err := cg.Wait()
1300         return rootdir + strings.Join(subdirs, ""), err
1301 }
1302
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))
1307         }
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
1312         // func.
1313         var pathparts []string
1314         // To reduce allocs, we reuse a single "toks" slice of 3 byte
1315         // slices.
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)
1322                 if c1 < 0 {
1323                         toks[0] = src
1324                         return 1
1325                 }
1326                 toks[0], src = src[:c1], src[c1+1:]
1327                 c2 := bytes.IndexRune(src, c)
1328                 if c2 < 0 {
1329                         toks[1] = src
1330                         return 2
1331                 }
1332                 toks[1], toks[2] = src[:c2], src[c2+1:]
1333                 return 3
1334         }
1335         for i, stream := range streams {
1336                 lineno := i + 1
1337                 var anyFileTokens bool
1338                 var pos int64
1339                 var segIdx int
1340                 segments = segments[:0]
1341                 pathparts = nil
1342                 streamparts := 0
1343                 for i, token := range bytes.Split(stream, []byte{' '}) {
1344                         if i == 0 {
1345                                 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1346                                 streamparts = len(pathparts)
1347                                 continue
1348                         }
1349                         if !bytes.ContainsRune(token, ':') {
1350                                 if anyFileTokens {
1351                                         return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1352                                 }
1353                                 if splitToToks(token, '+') < 2 {
1354                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1355                                 }
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)
1359                                 }
1360                                 segments = append(segments, storedSegment{
1361                                         locator: string(token),
1362                                         size:    int(length),
1363                                         offset:  0,
1364                                         length:  int(length),
1365                                 })
1366                                 continue
1367                         } else if len(segments) == 0 {
1368                                 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1369                         }
1370                         if splitToToks(token, ':') != 3 {
1371                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1372                         }
1373                         anyFileTokens = true
1374
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)
1378                         }
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)
1382                         }
1383                         if !bytes.ContainsAny(toks[2], `\/`) {
1384                                 // optimization for a common case
1385                                 pathparts = append(pathparts[:streamparts], string(toks[2]))
1386                         } else {
1387                                 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1388                         }
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.
1394                                 continue
1395                         }
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)
1398                         }
1399                         // Map the stream offset/range coordinates to
1400                         // block/offset/range coordinates and add
1401                         // corresponding storedSegments to the filenode
1402                         if pos > offset {
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)
1407                                 segIdx, pos = 0, 0
1408                         }
1409                         for ; segIdx < len(segments); segIdx++ {
1410                                 seg := segments[segIdx]
1411                                 next := pos + int64(seg.Len())
1412                                 if next <= offset || seg.Len() == 0 {
1413                                         pos = next
1414                                         continue
1415                                 }
1416                                 if pos >= offset+length {
1417                                         break
1418                                 }
1419                                 var blkOff int
1420                                 if pos < offset {
1421                                         blkOff = int(offset - pos)
1422                                 }
1423                                 blkLen := seg.Len() - blkOff
1424                                 if pos+int64(blkOff+blkLen) > offset+length {
1425                                         blkLen = int(offset + length - pos - int64(blkOff))
1426                                 }
1427                                 fnode.appendSegment(storedSegment{
1428                                         kc:      dn.fs,
1429                                         locator: seg.locator,
1430                                         size:    seg.size,
1431                                         offset:  blkOff,
1432                                         length:  blkLen,
1433                                 })
1434                                 if next > offset+length {
1435                                         break
1436                                 } else {
1437                                         pos = next
1438                                 }
1439                         }
1440                         if segIdx == len(segments) && pos < offset+length {
1441                                 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1442                         }
1443                 }
1444                 if !anyFileTokens {
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)
1450                 }
1451         }
1452         return nil
1453 }
1454
1455 // only safe to call from loadManifest -- no locking.
1456 //
1457 // If path is a "parent directory exists" marker (the last path
1458 // component is "."), the returned values are both nil.
1459 //
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) {
1463         var node inode = dn
1464         basename := names[len(names)-1]
1465         for _, name := range names[:len(names)-1] {
1466                 switch name {
1467                 case "", ".":
1468                         continue
1469                 case "..":
1470                         if node == dn {
1471                                 // can't be sure parent will be a *dirnode
1472                                 return nil, ErrInvalidArgument
1473                         }
1474                         node = node.Parent()
1475                         continue
1476                 }
1477                 node.Lock()
1478                 unlock := node.Unlock
1479                 node, err = node.Child(name, func(child inode) (inode, error) {
1480                         if child == nil {
1481                                 // note modtime will be fixed later in backdateTree()
1482                                 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1483                                 if err != nil {
1484                                         return nil, err
1485                                 }
1486                                 child.SetParent(node, name)
1487                                 return child, nil
1488                         } else if !child.IsDir() {
1489                                 return child, ErrFileExists
1490                         } else {
1491                                 return child, nil
1492                         }
1493                 })
1494                 unlock()
1495                 if err != nil {
1496                         return
1497                 }
1498         }
1499         if basename == "." {
1500                 return
1501         } else if !permittedName(basename) {
1502                 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1503                 return
1504         }
1505         node.Lock()
1506         defer node.Unlock()
1507         _, err = node.Child(basename, func(child inode) (inode, error) {
1508                 switch child := child.(type) {
1509                 case nil:
1510                         child, err = node.FS().newNode(basename, 0755, time.Time{})
1511                         if err != nil {
1512                                 return nil, err
1513                         }
1514                         child.SetParent(node, basename)
1515                         fn = child.(*filenode)
1516                         return child, nil
1517                 case *filenode:
1518                         fn = child
1519                         return child, nil
1520                 case *dirnode:
1521                         return child, ErrIsDirectory
1522                 default:
1523                         return child, ErrInvalidArgument
1524                 }
1525         })
1526         return
1527 }
1528
1529 func (dn *dirnode) TreeSize() (bytes int64) {
1530         dn.RLock()
1531         defer dn.RUnlock()
1532         for _, i := range dn.inodes {
1533                 switch i := i.(type) {
1534                 case *filenode:
1535                         bytes += i.Size()
1536                 case *dirnode:
1537                         bytes += i.TreeSize()
1538                 }
1539         }
1540         return
1541 }
1542
1543 func (dn *dirnode) Snapshot() (inode, error) {
1544         return dn.snapshot()
1545 }
1546
1547 func (dn *dirnode) snapshot() (*dirnode, error) {
1548         dn.RLock()
1549         defer dn.RUnlock()
1550         snap := &dirnode{
1551                 treenode: treenode{
1552                         inodes:   make(map[string]inode, len(dn.inodes)),
1553                         fileinfo: dn.fileinfo,
1554                 },
1555         }
1556         for name, child := range dn.inodes {
1557                 dupchild, err := child.Snapshot()
1558                 if err != nil {
1559                         return nil, err
1560                 }
1561                 snap.inodes[name] = dupchild
1562                 dupchild.SetParent(snap, name)
1563         }
1564         return snap, nil
1565 }
1566
1567 func (dn *dirnode) Splice(repl inode) error {
1568         repl, err := repl.Snapshot()
1569         if err != nil {
1570                 return fmt.Errorf("cannot copy snapshot: %w", err)
1571         }
1572         switch repl := repl.(type) {
1573         default:
1574                 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
1575         case *dirnode:
1576                 dn.Lock()
1577                 defer dn.Unlock()
1578                 dn.inodes = repl.inodes
1579                 dn.setTreeFS(dn.fs)
1580         case *filenode:
1581                 dn.parent.Lock()
1582                 defer dn.parent.Unlock()
1583                 removing, err := dn.parent.Child(dn.fileinfo.name, nil)
1584                 if err != 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
1595                                 // is inside it.)
1596                                 removing = deferred.realinode()
1597                         }
1598                         return fmt.Errorf("cannot use Splice to attach a file at top level of %T: %w", removing, ErrInvalidOperation)
1599                 }
1600                 dn.Lock()
1601                 defer dn.Unlock()
1602                 _, err = dn.parent.Child(dn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
1603                 if err != nil {
1604                         return fmt.Errorf("error replacing filenode: dn.parent.Child(): %w", err)
1605                 }
1606                 repl.fs = dn.fs
1607         }
1608         return nil
1609 }
1610
1611 func (dn *dirnode) setTreeFS(fs *collectionFileSystem) {
1612         dn.fs = fs
1613         for _, child := range dn.inodes {
1614                 switch child := child.(type) {
1615                 case *dirnode:
1616                         child.setTreeFS(fs)
1617                 case *filenode:
1618                         child.fs = fs
1619                 }
1620         }
1621 }
1622
1623 type segment interface {
1624         io.ReaderAt
1625         Len() int
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
1629 }
1630
1631 type memSegment struct {
1632         buf []byte
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{}
1638 }
1639
1640 func (me *memSegment) flushingUnfinished() bool {
1641         if me.flushing == nil {
1642                 return false
1643         }
1644         select {
1645         case <-me.flushing:
1646                 me.flushing = nil
1647                 return false
1648         default:
1649                 return true
1650         }
1651 }
1652
1653 func (me *memSegment) Len() int {
1654         return len(me.buf)
1655 }
1656
1657 func (me *memSegment) Slice(off, length int) segment {
1658         if length < 0 {
1659                 length = len(me.buf) - off
1660         }
1661         buf := make([]byte, length)
1662         copy(buf, me.buf[off:])
1663         return &memSegment{buf: buf}
1664 }
1665
1666 func (me *memSegment) Truncate(n int) {
1667         if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1668                 newsize := 1024
1669                 for newsize < n {
1670                         newsize = newsize << 2
1671                 }
1672                 newbuf := make([]byte, n, newsize)
1673                 copy(newbuf, me.buf)
1674                 me.buf, me.flushing = newbuf, nil
1675         } else {
1676                 // reclaim existing capacity, and zero reclaimed part
1677                 oldlen := len(me.buf)
1678                 me.buf = me.buf[:n]
1679                 for i := oldlen; i < n; i++ {
1680                         me.buf[i] = 0
1681                 }
1682         }
1683 }
1684
1685 func (me *memSegment) WriteAt(p []byte, off int) {
1686         if off+len(p) > len(me.buf) {
1687                 panic("overflowed segment")
1688         }
1689         if me.flushing != nil {
1690                 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1691         }
1692         copy(me.buf[off:], p)
1693 }
1694
1695 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1696         if off > int64(me.Len()) {
1697                 err = io.EOF
1698                 return
1699         }
1700         n = copy(p, me.buf[int(off):])
1701         if n < len(p) {
1702                 err = io.EOF
1703         }
1704         return
1705 }
1706
1707 type storedSegment struct {
1708         kc      fsBackend
1709         locator string
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)
1713 }
1714
1715 func (se storedSegment) Len() int {
1716         return se.length
1717 }
1718
1719 func (se storedSegment) Slice(n, size int) segment {
1720         se.offset += n
1721         se.length -= n
1722         if size >= 0 && se.length > size {
1723                 se.length = size
1724         }
1725         return se
1726 }
1727
1728 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1729         if off > int64(se.length) {
1730                 return 0, io.EOF
1731         }
1732         maxlen := se.length - int(off)
1733         if len(p) > maxlen {
1734                 p = p[:maxlen]
1735                 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1736                 if err == nil {
1737                         err = io.EOF
1738                 }
1739                 return
1740         }
1741         return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1742 }
1743
1744 func canonicalName(name string) string {
1745         name = path.Clean("/" + name)
1746         if name == "/" || name == "./" {
1747                 name = "."
1748         } else if strings.HasPrefix(name, "/") {
1749                 name = "." + name
1750         }
1751         return name
1752 }
1753
1754 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1755
1756 func manifestUnescapeFunc(seq string) string {
1757         if seq == `\\` {
1758                 return `\`
1759         }
1760         i, err := strconv.ParseUint(seq[1:], 8, 8)
1761         if err != nil {
1762                 // Invalid escape sequence: can't unescape.
1763                 return seq
1764         }
1765         return string([]byte{byte(i)})
1766 }
1767
1768 func manifestUnescape(s string) string {
1769         return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1770 }
1771
1772 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1773
1774 func manifestEscapeFunc(seq string) string {
1775         return fmt.Sprintf("\\%03o", byte(seq[0]))
1776 }
1777
1778 func manifestEscape(s string) string {
1779         return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)
1780 }