f4dae746e2a72a1a6384857749cf7261f5465917
[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                         for _, seg := range node.segments {
1163                                 switch seg := seg.(type) {
1164                                 case *memSegment:
1165                                         size += int64(seg.Len())
1166                                 }
1167                         }
1168                 }
1169         }
1170         return
1171 }
1172
1173 // caller must have write lock.
1174 func (dn *dirnode) sortedNames() []string {
1175         names := make([]string, 0, len(dn.inodes))
1176         for name := range dn.inodes {
1177                 names = append(names, name)
1178         }
1179         sort.Strings(names)
1180         return names
1181 }
1182
1183 // caller must have write lock.
1184 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1185         cg := newContextGroup(ctx)
1186         defer cg.Cancel()
1187
1188         if len(dn.inodes) == 0 {
1189                 if prefix == "." {
1190                         return "", nil
1191                 }
1192                 // Express the existence of an empty directory by
1193                 // adding an empty file named `\056`, which (unlike
1194                 // the more obvious spelling `.`) is accepted by the
1195                 // API's manifest validator.
1196                 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
1197         }
1198
1199         names := dn.sortedNames()
1200
1201         // Wait for children to finish any pending write operations
1202         // before locking them.
1203         for _, name := range names {
1204                 node := dn.inodes[name]
1205                 if fn, ok := node.(*filenode); ok {
1206                         fn.waitPrune()
1207                 }
1208         }
1209
1210         var dirnames []string
1211         var filenames []string
1212         for _, name := range names {
1213                 node := dn.inodes[name]
1214                 node.Lock()
1215                 defer node.Unlock()
1216                 switch node := node.(type) {
1217                 case *dirnode:
1218                         dirnames = append(dirnames, name)
1219                 case *filenode:
1220                         filenames = append(filenames, name)
1221                 default:
1222                         panic(fmt.Sprintf("can't marshal inode type %T", node))
1223                 }
1224         }
1225
1226         subdirs := make([]string, len(dirnames))
1227         rootdir := ""
1228         for i, name := range dirnames {
1229                 i, name := i, name
1230                 cg.Go(func() error {
1231                         txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1232                         subdirs[i] = txt
1233                         return err
1234                 })
1235         }
1236
1237         cg.Go(func() error {
1238                 var streamLen int64
1239                 type filepart struct {
1240                         name   string
1241                         offset int64
1242                         length int64
1243                 }
1244
1245                 var fileparts []filepart
1246                 var blocks []string
1247                 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1248                         return err
1249                 }
1250                 for _, name := range filenames {
1251                         node := dn.inodes[name].(*filenode)
1252                         if len(node.segments) == 0 {
1253                                 fileparts = append(fileparts, filepart{name: name})
1254                                 continue
1255                         }
1256                         for _, seg := range node.segments {
1257                                 switch seg := seg.(type) {
1258                                 case storedSegment:
1259                                         if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1260                                                 streamLen -= int64(seg.size)
1261                                         } else {
1262                                                 blocks = append(blocks, seg.locator)
1263                                         }
1264                                         next := filepart{
1265                                                 name:   name,
1266                                                 offset: streamLen + int64(seg.offset),
1267                                                 length: int64(seg.length),
1268                                         }
1269                                         if prev := len(fileparts) - 1; prev >= 0 &&
1270                                                 fileparts[prev].name == name &&
1271                                                 fileparts[prev].offset+fileparts[prev].length == next.offset {
1272                                                 fileparts[prev].length += next.length
1273                                         } else {
1274                                                 fileparts = append(fileparts, next)
1275                                         }
1276                                         streamLen += int64(seg.size)
1277                                 default:
1278                                         // This can't happen: we
1279                                         // haven't unlocked since
1280                                         // calling flush(sync=true).
1281                                         panic(fmt.Sprintf("can't marshal segment type %T", seg))
1282                                 }
1283                         }
1284                 }
1285                 var filetokens []string
1286                 for _, s := range fileparts {
1287                         filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1288                 }
1289                 if len(filetokens) == 0 {
1290                         return nil
1291                 } else if len(blocks) == 0 {
1292                         blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1293                 }
1294                 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1295                 return nil
1296         })
1297         err := cg.Wait()
1298         return rootdir + strings.Join(subdirs, ""), err
1299 }
1300
1301 func (dn *dirnode) loadManifest(txt string) error {
1302         streams := bytes.Split([]byte(txt), []byte{'\n'})
1303         if len(streams[len(streams)-1]) != 0 {
1304                 return fmt.Errorf("line %d: no trailing newline", len(streams))
1305         }
1306         streams = streams[:len(streams)-1]
1307         segments := []storedSegment{}
1308         // To reduce allocs, we reuse a single "pathparts" slice
1309         // (pre-split on "/" separators) for the duration of this
1310         // func.
1311         var pathparts []string
1312         // To reduce allocs, we reuse a single "toks" slice of 3 byte
1313         // slices.
1314         var toks = make([][]byte, 3)
1315         // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1316         // into the toks slice rather than allocating a new one, and
1317         // returns the number of toks (1, 2, or 3).
1318         splitToToks := func(src []byte, c rune) int {
1319                 c1 := bytes.IndexRune(src, c)
1320                 if c1 < 0 {
1321                         toks[0] = src
1322                         return 1
1323                 }
1324                 toks[0], src = src[:c1], src[c1+1:]
1325                 c2 := bytes.IndexRune(src, c)
1326                 if c2 < 0 {
1327                         toks[1] = src
1328                         return 2
1329                 }
1330                 toks[1], toks[2] = src[:c2], src[c2+1:]
1331                 return 3
1332         }
1333         for i, stream := range streams {
1334                 lineno := i + 1
1335                 var anyFileTokens bool
1336                 var pos int64
1337                 var segIdx int
1338                 segments = segments[:0]
1339                 pathparts = nil
1340                 streamparts := 0
1341                 for i, token := range bytes.Split(stream, []byte{' '}) {
1342                         if i == 0 {
1343                                 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1344                                 streamparts = len(pathparts)
1345                                 continue
1346                         }
1347                         if !bytes.ContainsRune(token, ':') {
1348                                 if anyFileTokens {
1349                                         return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1350                                 }
1351                                 if splitToToks(token, '+') < 2 {
1352                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1353                                 }
1354                                 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1355                                 if err != nil || length < 0 {
1356                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1357                                 }
1358                                 segments = append(segments, storedSegment{
1359                                         locator: string(token),
1360                                         size:    int(length),
1361                                         offset:  0,
1362                                         length:  int(length),
1363                                 })
1364                                 continue
1365                         } else if len(segments) == 0 {
1366                                 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1367                         }
1368                         if splitToToks(token, ':') != 3 {
1369                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1370                         }
1371                         anyFileTokens = true
1372
1373                         offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1374                         if err != nil || offset < 0 {
1375                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1376                         }
1377                         length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1378                         if err != nil || length < 0 {
1379                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1380                         }
1381                         if !bytes.ContainsAny(toks[2], `\/`) {
1382                                 // optimization for a common case
1383                                 pathparts = append(pathparts[:streamparts], string(toks[2]))
1384                         } else {
1385                                 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1386                         }
1387                         fnode, err := dn.createFileAndParents(pathparts)
1388                         if fnode == nil && err == nil && length == 0 {
1389                                 // Special case: an empty file used as
1390                                 // a marker to preserve an otherwise
1391                                 // empty directory in a manifest.
1392                                 continue
1393                         }
1394                         if err != nil || (fnode == nil && length != 0) {
1395                                 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1396                         }
1397                         // Map the stream offset/range coordinates to
1398                         // block/offset/range coordinates and add
1399                         // corresponding storedSegments to the filenode
1400                         if pos > offset {
1401                                 // Can't continue where we left off.
1402                                 // TODO: binary search instead of
1403                                 // rewinding all the way (but this
1404                                 // situation might be rare anyway)
1405                                 segIdx, pos = 0, 0
1406                         }
1407                         for ; segIdx < len(segments); segIdx++ {
1408                                 seg := segments[segIdx]
1409                                 next := pos + int64(seg.Len())
1410                                 if next <= offset || seg.Len() == 0 {
1411                                         pos = next
1412                                         continue
1413                                 }
1414                                 if pos >= offset+length {
1415                                         break
1416                                 }
1417                                 var blkOff int
1418                                 if pos < offset {
1419                                         blkOff = int(offset - pos)
1420                                 }
1421                                 blkLen := seg.Len() - blkOff
1422                                 if pos+int64(blkOff+blkLen) > offset+length {
1423                                         blkLen = int(offset + length - pos - int64(blkOff))
1424                                 }
1425                                 fnode.appendSegment(storedSegment{
1426                                         kc:      dn.fs,
1427                                         locator: seg.locator,
1428                                         size:    seg.size,
1429                                         offset:  blkOff,
1430                                         length:  blkLen,
1431                                 })
1432                                 if next > offset+length {
1433                                         break
1434                                 } else {
1435                                         pos = next
1436                                 }
1437                         }
1438                         if segIdx == len(segments) && pos < offset+length {
1439                                 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1440                         }
1441                 }
1442                 if !anyFileTokens {
1443                         return fmt.Errorf("line %d: no file segments", lineno)
1444                 } else if len(segments) == 0 {
1445                         return fmt.Errorf("line %d: no locators", lineno)
1446                 } else if streamparts == 0 {
1447                         return fmt.Errorf("line %d: no stream name", lineno)
1448                 }
1449         }
1450         return nil
1451 }
1452
1453 // only safe to call from loadManifest -- no locking.
1454 //
1455 // If path is a "parent directory exists" marker (the last path
1456 // component is "."), the returned values are both nil.
1457 //
1458 // Newly added nodes have modtime==0. Caller is responsible for fixing
1459 // them with backdateTree.
1460 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1461         var node inode = dn
1462         basename := names[len(names)-1]
1463         for _, name := range names[:len(names)-1] {
1464                 switch name {
1465                 case "", ".":
1466                         continue
1467                 case "..":
1468                         if node == dn {
1469                                 // can't be sure parent will be a *dirnode
1470                                 return nil, ErrInvalidArgument
1471                         }
1472                         node = node.Parent()
1473                         continue
1474                 }
1475                 node.Lock()
1476                 unlock := node.Unlock
1477                 node, err = node.Child(name, func(child inode) (inode, error) {
1478                         if child == nil {
1479                                 // note modtime will be fixed later in backdateTree()
1480                                 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1481                                 if err != nil {
1482                                         return nil, err
1483                                 }
1484                                 child.SetParent(node, name)
1485                                 return child, nil
1486                         } else if !child.IsDir() {
1487                                 return child, ErrFileExists
1488                         } else {
1489                                 return child, nil
1490                         }
1491                 })
1492                 unlock()
1493                 if err != nil {
1494                         return
1495                 }
1496         }
1497         if basename == "." {
1498                 return
1499         } else if !permittedName(basename) {
1500                 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1501                 return
1502         }
1503         node.Lock()
1504         defer node.Unlock()
1505         _, err = node.Child(basename, func(child inode) (inode, error) {
1506                 switch child := child.(type) {
1507                 case nil:
1508                         child, err = node.FS().newNode(basename, 0755, time.Time{})
1509                         if err != nil {
1510                                 return nil, err
1511                         }
1512                         child.SetParent(node, basename)
1513                         fn = child.(*filenode)
1514                         return child, nil
1515                 case *filenode:
1516                         fn = child
1517                         return child, nil
1518                 case *dirnode:
1519                         return child, ErrIsDirectory
1520                 default:
1521                         return child, ErrInvalidArgument
1522                 }
1523         })
1524         return
1525 }
1526
1527 func (dn *dirnode) TreeSize() (bytes int64) {
1528         dn.RLock()
1529         defer dn.RUnlock()
1530         for _, i := range dn.inodes {
1531                 switch i := i.(type) {
1532                 case *filenode:
1533                         bytes += i.Size()
1534                 case *dirnode:
1535                         bytes += i.TreeSize()
1536                 }
1537         }
1538         return
1539 }
1540
1541 func (dn *dirnode) Snapshot() (inode, error) {
1542         return dn.snapshot()
1543 }
1544
1545 func (dn *dirnode) snapshot() (*dirnode, error) {
1546         dn.RLock()
1547         defer dn.RUnlock()
1548         snap := &dirnode{
1549                 treenode: treenode{
1550                         inodes:   make(map[string]inode, len(dn.inodes)),
1551                         fileinfo: dn.fileinfo,
1552                 },
1553         }
1554         for name, child := range dn.inodes {
1555                 dupchild, err := child.Snapshot()
1556                 if err != nil {
1557                         return nil, err
1558                 }
1559                 snap.inodes[name] = dupchild
1560                 dupchild.SetParent(snap, name)
1561         }
1562         return snap, nil
1563 }
1564
1565 func (dn *dirnode) Splice(repl inode) error {
1566         repl, err := repl.Snapshot()
1567         if err != nil {
1568                 return fmt.Errorf("cannot copy snapshot: %w", err)
1569         }
1570         switch repl := repl.(type) {
1571         default:
1572                 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
1573         case *dirnode:
1574                 dn.Lock()
1575                 defer dn.Unlock()
1576                 dn.inodes = repl.inodes
1577                 dn.setTreeFS(dn.fs)
1578         case *filenode:
1579                 dn.parent.Lock()
1580                 defer dn.parent.Unlock()
1581                 removing, err := dn.parent.Child(dn.fileinfo.name, nil)
1582                 if err != nil {
1583                         return fmt.Errorf("cannot use Splice to replace a top-level directory with a file: %w", ErrInvalidOperation)
1584                 } else if removing != dn {
1585                         // If ../thisdirname is not this dirnode, it
1586                         // must be an inode that wraps a dirnode, like
1587                         // a collectionFileSystem or deferrednode.
1588                         if deferred, ok := removing.(*deferrednode); ok {
1589                                 // More useful to report the type of
1590                                 // the wrapped node rather than just
1591                                 // *deferrednode. (We know the real
1592                                 // inode is already loaded because dn
1593                                 // is inside it.)
1594                                 removing = deferred.realinode()
1595                         }
1596                         return fmt.Errorf("cannot use Splice to attach a file at top level of %T: %w", removing, ErrInvalidOperation)
1597                 }
1598                 dn.Lock()
1599                 defer dn.Unlock()
1600                 _, err = dn.parent.Child(dn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
1601                 if err != nil {
1602                         return fmt.Errorf("error replacing filenode: dn.parent.Child(): %w", err)
1603                 }
1604                 repl.fs = dn.fs
1605         }
1606         return nil
1607 }
1608
1609 func (dn *dirnode) setTreeFS(fs *collectionFileSystem) {
1610         dn.fs = fs
1611         for _, child := range dn.inodes {
1612                 switch child := child.(type) {
1613                 case *dirnode:
1614                         child.setTreeFS(fs)
1615                 case *filenode:
1616                         child.fs = fs
1617                 }
1618         }
1619 }
1620
1621 type segment interface {
1622         io.ReaderAt
1623         Len() int
1624         // Return a new segment with a subsection of the data from this
1625         // one. length<0 means length=Len()-off.
1626         Slice(off int, length int) segment
1627 }
1628
1629 type memSegment struct {
1630         buf []byte
1631         // If flushing is not nil and not ready/closed, then a) buf is
1632         // being shared by a pruneMemSegments goroutine, and must be
1633         // copied on write; and b) the flushing channel will close
1634         // when the goroutine finishes, whether it succeeds or not.
1635         flushing <-chan struct{}
1636 }
1637
1638 func (me *memSegment) flushingUnfinished() bool {
1639         if me.flushing == nil {
1640                 return false
1641         }
1642         select {
1643         case <-me.flushing:
1644                 me.flushing = nil
1645                 return false
1646         default:
1647                 return true
1648         }
1649 }
1650
1651 func (me *memSegment) Len() int {
1652         return len(me.buf)
1653 }
1654
1655 func (me *memSegment) Slice(off, length int) segment {
1656         if length < 0 {
1657                 length = len(me.buf) - off
1658         }
1659         buf := make([]byte, length)
1660         copy(buf, me.buf[off:])
1661         return &memSegment{buf: buf}
1662 }
1663
1664 func (me *memSegment) Truncate(n int) {
1665         if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1666                 newsize := 1024
1667                 for newsize < n {
1668                         newsize = newsize << 2
1669                 }
1670                 newbuf := make([]byte, n, newsize)
1671                 copy(newbuf, me.buf)
1672                 me.buf, me.flushing = newbuf, nil
1673         } else {
1674                 // reclaim existing capacity, and zero reclaimed part
1675                 oldlen := len(me.buf)
1676                 me.buf = me.buf[:n]
1677                 for i := oldlen; i < n; i++ {
1678                         me.buf[i] = 0
1679                 }
1680         }
1681 }
1682
1683 func (me *memSegment) WriteAt(p []byte, off int) {
1684         if off+len(p) > len(me.buf) {
1685                 panic("overflowed segment")
1686         }
1687         if me.flushing != nil {
1688                 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1689         }
1690         copy(me.buf[off:], p)
1691 }
1692
1693 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1694         if off > int64(me.Len()) {
1695                 err = io.EOF
1696                 return
1697         }
1698         n = copy(p, me.buf[int(off):])
1699         if n < len(p) {
1700                 err = io.EOF
1701         }
1702         return
1703 }
1704
1705 type storedSegment struct {
1706         kc      fsBackend
1707         locator string
1708         size    int // size of stored block (also encoded in locator)
1709         offset  int // position of segment within the stored block
1710         length  int // bytes in this segment (offset + length <= size)
1711 }
1712
1713 func (se storedSegment) Len() int {
1714         return se.length
1715 }
1716
1717 func (se storedSegment) Slice(n, size int) segment {
1718         se.offset += n
1719         se.length -= n
1720         if size >= 0 && se.length > size {
1721                 se.length = size
1722         }
1723         return se
1724 }
1725
1726 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1727         if off > int64(se.length) {
1728                 return 0, io.EOF
1729         }
1730         maxlen := se.length - int(off)
1731         if len(p) > maxlen {
1732                 p = p[:maxlen]
1733                 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1734                 if err == nil {
1735                         err = io.EOF
1736                 }
1737                 return
1738         }
1739         return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1740 }
1741
1742 func canonicalName(name string) string {
1743         name = path.Clean("/" + name)
1744         if name == "/" || name == "./" {
1745                 name = "."
1746         } else if strings.HasPrefix(name, "/") {
1747                 name = "." + name
1748         }
1749         return name
1750 }
1751
1752 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1753
1754 func manifestUnescapeFunc(seq string) string {
1755         if seq == `\\` {
1756                 return `\`
1757         }
1758         i, err := strconv.ParseUint(seq[1:], 8, 8)
1759         if err != nil {
1760                 // Invalid escape sequence: can't unescape.
1761                 return seq
1762         }
1763         return string([]byte{byte(i)})
1764 }
1765
1766 func manifestUnescape(s string) string {
1767         return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1768 }
1769
1770 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1771
1772 func manifestEscapeFunc(seq string) string {
1773         return fmt.Sprintf("\\%03o", byte(seq[0]))
1774 }
1775
1776 func manifestEscape(s string) string {
1777         return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)
1778 }