19368: Skip regenerating manifest during webdav/s3 logging.
[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                                 sys:     func() interface{} { return c },
89                         },
90                         inodes: make(map[string]inode),
91                 },
92         }
93         root.SetParent(root, ".")
94         if err := root.loadManifest(c.ManifestText); err != nil {
95                 return nil, err
96         }
97         backdateTree(root, modTime)
98         fs.root = root
99         return fs, nil
100 }
101
102 // caller must have lock (or guarantee no concurrent accesses somehow)
103 func eachNode(n inode, ffunc func(*filenode), dfunc func(*dirnode)) {
104         switch n := n.(type) {
105         case *filenode:
106                 if ffunc != nil {
107                         ffunc(n)
108                 }
109         case *dirnode:
110                 if dfunc != nil {
111                         dfunc(n)
112                 }
113                 for _, n := range n.inodes {
114                         eachNode(n, ffunc, dfunc)
115                 }
116         }
117 }
118
119 // caller must have lock (or guarantee no concurrent accesses somehow)
120 func backdateTree(n inode, modTime time.Time) {
121         eachNode(n, func(fn *filenode) {
122                 fn.fileinfo.modTime = modTime
123         }, func(dn *dirnode) {
124                 dn.fileinfo.modTime = modTime
125         })
126 }
127
128 // Approximate portion of signature TTL remaining, usually between 0
129 // and 1, or negative if some signatures have expired.
130 func (fs *collectionFileSystem) signatureTimeLeft() (float64, time.Duration) {
131         var (
132                 now      = time.Now()
133                 earliest = now.Add(time.Hour * 24 * 7 * 365)
134                 latest   time.Time
135         )
136         fs.fileSystem.root.RLock()
137         eachNode(fs.root, func(fn *filenode) {
138                 fn.Lock()
139                 defer fn.Unlock()
140                 for _, seg := range fn.segments {
141                         seg, ok := seg.(storedSegment)
142                         if !ok {
143                                 continue
144                         }
145                         expiryTime, err := signatureExpiryTime(seg.locator)
146                         if err != nil {
147                                 continue
148                         }
149                         if expiryTime.Before(earliest) {
150                                 earliest = expiryTime
151                         }
152                         if expiryTime.After(latest) {
153                                 latest = expiryTime
154                         }
155                 }
156         }, nil)
157         fs.fileSystem.root.RUnlock()
158
159         if latest.IsZero() {
160                 // No signatures == 100% of TTL remaining.
161                 return 1, 1
162         }
163
164         ttl := latest.Sub(now)
165         fs.fileSystem.root.Lock()
166         {
167                 if ttl > fs.guessSignatureTTL {
168                         // ttl is closer to the real TTL than
169                         // guessSignatureTTL.
170                         fs.guessSignatureTTL = ttl
171                 } else {
172                         // Use the previous best guess to compute the
173                         // portion remaining (below, after unlocking
174                         // mutex).
175                         ttl = fs.guessSignatureTTL
176                 }
177         }
178         fs.fileSystem.root.Unlock()
179
180         return earliest.Sub(now).Seconds() / ttl.Seconds(), ttl
181 }
182
183 func (fs *collectionFileSystem) updateSignatures(newmanifest string) {
184         newLoc := map[string]string{}
185         for _, tok := range regexp.MustCompile(`\S+`).FindAllString(newmanifest, -1) {
186                 if mBlkRe.MatchString(tok) {
187                         newLoc[stripAllHints(tok)] = tok
188                 }
189         }
190         fs.fileSystem.root.Lock()
191         defer fs.fileSystem.root.Unlock()
192         eachNode(fs.root, func(fn *filenode) {
193                 fn.Lock()
194                 defer fn.Unlock()
195                 for idx, seg := range fn.segments {
196                         seg, ok := seg.(storedSegment)
197                         if !ok {
198                                 continue
199                         }
200                         loc, ok := newLoc[stripAllHints(seg.locator)]
201                         if !ok {
202                                 continue
203                         }
204                         seg.locator = loc
205                         fn.segments[idx] = seg
206                 }
207         }, nil)
208 }
209
210 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
211         if name == "" || name == "." || name == ".." {
212                 return nil, ErrInvalidArgument
213         }
214         if perm.IsDir() {
215                 return &dirnode{
216                         fs: fs,
217                         treenode: treenode{
218                                 fileinfo: fileinfo{
219                                         name:    name,
220                                         mode:    perm | os.ModeDir,
221                                         modTime: modTime,
222                                 },
223                                 inodes: make(map[string]inode),
224                         },
225                 }, nil
226         }
227         return &filenode{
228                 fs: fs,
229                 fileinfo: fileinfo{
230                         name:    name,
231                         mode:    perm & ^os.ModeDir,
232                         modTime: modTime,
233                 },
234         }, nil
235 }
236
237 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
238         return fs.rootnode().Child(name, replace)
239 }
240
241 func (fs *collectionFileSystem) FS() FileSystem {
242         return fs
243 }
244
245 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
246         return fs.rootnode().FileInfo()
247 }
248
249 func (fs *collectionFileSystem) IsDir() bool {
250         return true
251 }
252
253 func (fs *collectionFileSystem) Lock() {
254         fs.rootnode().Lock()
255 }
256
257 func (fs *collectionFileSystem) Unlock() {
258         fs.rootnode().Unlock()
259 }
260
261 func (fs *collectionFileSystem) RLock() {
262         fs.rootnode().RLock()
263 }
264
265 func (fs *collectionFileSystem) RUnlock() {
266         fs.rootnode().RUnlock()
267 }
268
269 func (fs *collectionFileSystem) Parent() inode {
270         return fs.rootnode().Parent()
271 }
272
273 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
274         return 0, ptr, ErrInvalidOperation
275 }
276
277 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
278         return 0, ptr, ErrInvalidOperation
279 }
280
281 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
282         return fs.rootnode().Readdir()
283 }
284
285 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
286         fs.rootnode().SetParent(parent, name)
287 }
288
289 func (fs *collectionFileSystem) Truncate(int64) error {
290         return ErrInvalidOperation
291 }
292
293 // Check for and incorporate upstream changes -- unless that has
294 // already been done recently, in which case this func is a no-op.
295 func (fs *collectionFileSystem) checkChangesOnServer() error {
296         if fs.uuid == "" && fs.savedPDH.Load() == "" {
297                 return nil
298         }
299
300         // First try UUID if any, then last known PDH. Stop if all
301         // signatures are new enough.
302         checkingAll := false
303         for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
304                 if id == "" {
305                         continue
306                 }
307
308                 fs.lockCheckChanges.Lock()
309                 if !checkingAll && fs.holdCheckChanges.After(time.Now()) {
310                         fs.lockCheckChanges.Unlock()
311                         return nil
312                 }
313                 remain, ttl := fs.signatureTimeLeft()
314                 if remain > 0.01 && !checkingAll {
315                         fs.holdCheckChanges = time.Now().Add(ttl / 100)
316                 }
317                 fs.lockCheckChanges.Unlock()
318
319                 if remain >= 0.5 {
320                         break
321                 }
322                 checkingAll = true
323                 var coll Collection
324                 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
325                 if err != nil {
326                         continue
327                 }
328                 fs.updateSignatures(coll.ManifestText)
329         }
330         return nil
331 }
332
333 // Refresh signature on a single locator, if necessary. Assume caller
334 // has lock. If an update is needed, and there are any storedSegments
335 // whose signatures can be updated, start a background task to update
336 // them asynchronously when the caller releases locks.
337 func (fs *collectionFileSystem) refreshSignature(locator string) string {
338         exp, err := signatureExpiryTime(locator)
339         if err != nil || exp.Sub(time.Now()) > time.Minute {
340                 // Synchronous update is not needed. Start an
341                 // asynchronous update if needed.
342                 go fs.checkChangesOnServer()
343                 return locator
344         }
345         var manifests string
346         for _, id := range []string{fs.uuid, fs.savedPDH.Load().(string)} {
347                 if id == "" {
348                         continue
349                 }
350                 var coll Collection
351                 err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, map[string]interface{}{"select": []string{"portable_data_hash", "manifest_text"}})
352                 if err != nil {
353                         continue
354                 }
355                 manifests += coll.ManifestText
356         }
357         hash := stripAllHints(locator)
358         for _, tok := range regexp.MustCompile(`\S+`).FindAllString(manifests, -1) {
359                 if mBlkRe.MatchString(tok) {
360                         if stripAllHints(tok) == hash {
361                                 locator = tok
362                                 break
363                         }
364                 }
365         }
366         go fs.updateSignatures(manifests)
367         return locator
368 }
369
370 func (fs *collectionFileSystem) Sync() error {
371         err := fs.checkChangesOnServer()
372         if err != nil {
373                 return err
374         }
375         if fs.uuid == "" {
376                 return nil
377         }
378         txt, err := fs.MarshalManifest(".")
379         if err != nil {
380                 return fmt.Errorf("sync failed: %s", err)
381         }
382         if PortableDataHash(txt) == fs.savedPDH.Load() {
383                 // No local changes since last save or initial load.
384                 return nil
385         }
386         coll := Collection{
387                 UUID:         fs.uuid,
388                 ManifestText: txt,
389         }
390
391         selectFields := []string{"uuid", "portable_data_hash"}
392         fs.lockCheckChanges.Lock()
393         remain, _ := fs.signatureTimeLeft()
394         fs.lockCheckChanges.Unlock()
395         if remain < 0.5 {
396                 selectFields = append(selectFields, "manifest_text")
397         }
398
399         err = fs.RequestAndDecode(&coll, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
400                 "collection": map[string]string{
401                         "manifest_text": coll.ManifestText,
402                 },
403                 "select": selectFields,
404         })
405         if err != nil {
406                 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
407         }
408         fs.updateSignatures(coll.ManifestText)
409         fs.savedPDH.Store(coll.PortableDataHash)
410         return nil
411 }
412
413 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
414         node, err := rlookup(fs.fileSystem.root, path)
415         if err != nil {
416                 return err
417         }
418         dn, ok := node.(*dirnode)
419         if !ok {
420                 return ErrNotADirectory
421         }
422         dn.Lock()
423         defer dn.Unlock()
424         names := dn.sortedNames()
425         if path != "" {
426                 // Caller only wants to flush the specified dir,
427                 // non-recursively.  Drop subdirs from the list of
428                 // names.
429                 var filenames []string
430                 for _, name := range names {
431                         if _, ok := dn.inodes[name].(*filenode); ok {
432                                 filenames = append(filenames, name)
433                         }
434                 }
435                 names = filenames
436         }
437         for _, name := range names {
438                 child := dn.inodes[name]
439                 child.Lock()
440                 defer child.Unlock()
441         }
442         return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
443 }
444
445 func (fs *collectionFileSystem) MemorySize() int64 {
446         fs.fileSystem.root.Lock()
447         defer fs.fileSystem.root.Unlock()
448         return fs.fileSystem.root.(*dirnode).MemorySize()
449 }
450
451 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
452         fs.fileSystem.root.Lock()
453         defer fs.fileSystem.root.Unlock()
454         return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
455 }
456
457 func (fs *collectionFileSystem) Size() int64 {
458         return fs.fileSystem.root.(*dirnode).TreeSize()
459 }
460
461 func (fs *collectionFileSystem) Snapshot() (inode, error) {
462         return fs.fileSystem.root.Snapshot()
463 }
464
465 func (fs *collectionFileSystem) Splice(r inode) error {
466         return fs.fileSystem.root.Splice(r)
467 }
468
469 // filenodePtr is an offset into a file that is (usually) efficient to
470 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
471 // then
472 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
473 // corresponds to file offset filenodePtr.off. Otherwise, it is
474 // necessary to reexamine len(filenode.segments[0]) etc. to find the
475 // correct segment and offset.
476 type filenodePtr struct {
477         off        int64
478         segmentIdx int
479         segmentOff int
480         repacked   int64
481 }
482
483 // seek returns a ptr that is consistent with both startPtr.off and
484 // the current state of fn. The caller must already hold fn.RLock() or
485 // fn.Lock().
486 //
487 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
488 // EOF.
489 //
490 // After seeking:
491 //
492 //     ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
493 //     ||
494 //     filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
495 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
496         ptr = startPtr
497         if ptr.off < 0 {
498                 // meaningless anyway
499                 return
500         } else if ptr.off >= fn.fileinfo.size {
501                 ptr.segmentIdx = len(fn.segments)
502                 ptr.segmentOff = 0
503                 ptr.repacked = fn.repacked
504                 return
505         } else if ptr.repacked == fn.repacked {
506                 // segmentIdx and segmentOff accurately reflect
507                 // ptr.off, but might have fallen off the end of a
508                 // segment
509                 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
510                         ptr.segmentIdx++
511                         ptr.segmentOff = 0
512                 }
513                 return
514         }
515         defer func() {
516                 ptr.repacked = fn.repacked
517         }()
518         if ptr.off >= fn.fileinfo.size {
519                 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
520                 return
521         }
522         // Recompute segmentIdx and segmentOff.  We have already
523         // established fn.fileinfo.size > ptr.off >= 0, so we don't
524         // have to deal with edge cases here.
525         var off int64
526         for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
527                 // This would panic (index out of range) if
528                 // fn.fileinfo.size were larger than
529                 // sum(fn.segments[i].Len()) -- but that can't happen
530                 // because we have ensured fn.fileinfo.size is always
531                 // accurate.
532                 segLen := int64(fn.segments[ptr.segmentIdx].Len())
533                 if off+segLen > ptr.off {
534                         ptr.segmentOff = int(ptr.off - off)
535                         break
536                 }
537                 off += segLen
538         }
539         return
540 }
541
542 // filenode implements inode.
543 type filenode struct {
544         parent   inode
545         fs       *collectionFileSystem
546         fileinfo fileinfo
547         segments []segment
548         // number of times `segments` has changed in a
549         // way that might invalidate a filenodePtr
550         repacked int64
551         memsize  int64 // bytes in memSegments
552         sync.RWMutex
553         nullnode
554 }
555
556 // caller must have lock
557 func (fn *filenode) appendSegment(e segment) {
558         fn.segments = append(fn.segments, e)
559         fn.fileinfo.size += int64(e.Len())
560 }
561
562 func (fn *filenode) SetParent(p inode, name string) {
563         fn.Lock()
564         defer fn.Unlock()
565         fn.parent = p
566         fn.fileinfo.name = name
567 }
568
569 func (fn *filenode) Parent() inode {
570         fn.RLock()
571         defer fn.RUnlock()
572         return fn.parent
573 }
574
575 func (fn *filenode) FS() FileSystem {
576         return fn.fs
577 }
578
579 // Read reads file data from a single segment, starting at startPtr,
580 // into p. startPtr is assumed not to be up-to-date. Caller must have
581 // RLock or Lock.
582 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
583         ptr = fn.seek(startPtr)
584         if ptr.off < 0 {
585                 err = ErrNegativeOffset
586                 return
587         }
588         if ptr.segmentIdx >= len(fn.segments) {
589                 err = io.EOF
590                 return
591         }
592         if ss, ok := fn.segments[ptr.segmentIdx].(storedSegment); ok {
593                 ss.locator = fn.fs.refreshSignature(ss.locator)
594                 fn.segments[ptr.segmentIdx] = ss
595         }
596         n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
597         if n > 0 {
598                 ptr.off += int64(n)
599                 ptr.segmentOff += n
600                 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
601                         ptr.segmentIdx++
602                         ptr.segmentOff = 0
603                         if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
604                                 err = nil
605                         }
606                 }
607         }
608         return
609 }
610
611 func (fn *filenode) Size() int64 {
612         fn.RLock()
613         defer fn.RUnlock()
614         return fn.fileinfo.Size()
615 }
616
617 func (fn *filenode) FileInfo() os.FileInfo {
618         fn.RLock()
619         defer fn.RUnlock()
620         return fn.fileinfo
621 }
622
623 func (fn *filenode) Truncate(size int64) error {
624         fn.Lock()
625         defer fn.Unlock()
626         return fn.truncate(size)
627 }
628
629 func (fn *filenode) truncate(size int64) error {
630         if size == fn.fileinfo.size {
631                 return nil
632         }
633         fn.repacked++
634         if size < fn.fileinfo.size {
635                 ptr := fn.seek(filenodePtr{off: size})
636                 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
637                         if seg, ok := fn.segments[i].(*memSegment); ok {
638                                 fn.memsize -= int64(seg.Len())
639                         }
640                 }
641                 if ptr.segmentOff == 0 {
642                         fn.segments = fn.segments[:ptr.segmentIdx]
643                 } else {
644                         fn.segments = fn.segments[:ptr.segmentIdx+1]
645                         switch seg := fn.segments[ptr.segmentIdx].(type) {
646                         case *memSegment:
647                                 seg.Truncate(ptr.segmentOff)
648                                 fn.memsize += int64(seg.Len())
649                         default:
650                                 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
651                         }
652                 }
653                 fn.fileinfo.size = size
654                 return nil
655         }
656         for size > fn.fileinfo.size {
657                 grow := size - fn.fileinfo.size
658                 var seg *memSegment
659                 var ok bool
660                 if len(fn.segments) == 0 {
661                         seg = &memSegment{}
662                         fn.segments = append(fn.segments, seg)
663                 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
664                         seg = &memSegment{}
665                         fn.segments = append(fn.segments, seg)
666                 }
667                 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
668                         grow = maxgrow
669                 }
670                 seg.Truncate(seg.Len() + int(grow))
671                 fn.fileinfo.size += grow
672                 fn.memsize += grow
673         }
674         return nil
675 }
676
677 // Write writes data from p to the file, starting at startPtr,
678 // extending the file size if necessary. Caller must have Lock.
679 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
680         if startPtr.off > fn.fileinfo.size {
681                 if err = fn.truncate(startPtr.off); err != nil {
682                         return 0, startPtr, err
683                 }
684         }
685         ptr = fn.seek(startPtr)
686         if ptr.off < 0 {
687                 err = ErrNegativeOffset
688                 return
689         }
690         for len(p) > 0 && err == nil {
691                 cando := p
692                 if len(cando) > maxBlockSize {
693                         cando = cando[:maxBlockSize]
694                 }
695                 // Rearrange/grow fn.segments (and shrink cando if
696                 // needed) such that cando can be copied to
697                 // fn.segments[ptr.segmentIdx] at offset
698                 // ptr.segmentOff.
699                 cur := ptr.segmentIdx
700                 prev := ptr.segmentIdx - 1
701                 var curWritable bool
702                 if cur < len(fn.segments) {
703                         _, curWritable = fn.segments[cur].(*memSegment)
704                 }
705                 var prevAppendable bool
706                 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
707                         _, prevAppendable = fn.segments[prev].(*memSegment)
708                 }
709                 if ptr.segmentOff > 0 && !curWritable {
710                         // Split a non-writable block.
711                         if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
712                                 // Truncate cur, and insert a new
713                                 // segment after it.
714                                 cando = cando[:max]
715                                 fn.segments = append(fn.segments, nil)
716                                 copy(fn.segments[cur+1:], fn.segments[cur:])
717                         } else {
718                                 // Split cur into two copies, truncate
719                                 // the one on the left, shift the one
720                                 // on the right, and insert a new
721                                 // segment between them.
722                                 fn.segments = append(fn.segments, nil, nil)
723                                 copy(fn.segments[cur+2:], fn.segments[cur:])
724                                 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
725                         }
726                         cur++
727                         prev++
728                         seg := &memSegment{}
729                         seg.Truncate(len(cando))
730                         fn.memsize += int64(len(cando))
731                         fn.segments[cur] = seg
732                         fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
733                         ptr.segmentIdx++
734                         ptr.segmentOff = 0
735                         fn.repacked++
736                         ptr.repacked++
737                 } else if curWritable {
738                         if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
739                                 cando = cando[:fit]
740                         }
741                 } else {
742                         if prevAppendable {
743                                 // Shrink cando if needed to fit in
744                                 // prev segment.
745                                 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
746                                         cando = cando[:cangrow]
747                                 }
748                         }
749
750                         if cur == len(fn.segments) {
751                                 // ptr is at EOF, filesize is changing.
752                                 fn.fileinfo.size += int64(len(cando))
753                         } else if el := fn.segments[cur].Len(); el <= len(cando) {
754                                 // cando is long enough that we won't
755                                 // need cur any more. shrink cando to
756                                 // be exactly as long as cur
757                                 // (otherwise we'd accidentally shift
758                                 // the effective position of all
759                                 // segments after cur).
760                                 cando = cando[:el]
761                                 copy(fn.segments[cur:], fn.segments[cur+1:])
762                                 fn.segments = fn.segments[:len(fn.segments)-1]
763                         } else {
764                                 // shrink cur by the same #bytes we're growing prev
765                                 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
766                         }
767
768                         if prevAppendable {
769                                 // Grow prev.
770                                 ptr.segmentIdx--
771                                 ptr.segmentOff = fn.segments[prev].Len()
772                                 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
773                                 fn.memsize += int64(len(cando))
774                                 ptr.repacked++
775                                 fn.repacked++
776                         } else {
777                                 // Insert a segment between prev and
778                                 // cur, and advance prev/cur.
779                                 fn.segments = append(fn.segments, nil)
780                                 if cur < len(fn.segments) {
781                                         copy(fn.segments[cur+1:], fn.segments[cur:])
782                                         ptr.repacked++
783                                         fn.repacked++
784                                 } else {
785                                         // appending a new segment does
786                                         // not invalidate any ptrs
787                                 }
788                                 seg := &memSegment{}
789                                 seg.Truncate(len(cando))
790                                 fn.memsize += int64(len(cando))
791                                 fn.segments[cur] = seg
792                         }
793                 }
794
795                 // Finally we can copy bytes from cando to the current segment.
796                 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
797                 n += len(cando)
798                 p = p[len(cando):]
799
800                 ptr.off += int64(len(cando))
801                 ptr.segmentOff += len(cando)
802                 if ptr.segmentOff >= maxBlockSize {
803                         fn.pruneMemSegments()
804                 }
805                 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
806                         ptr.segmentOff = 0
807                         ptr.segmentIdx++
808                 }
809
810                 fn.fileinfo.modTime = time.Now()
811         }
812         return
813 }
814
815 // Write some data out to disk to reduce memory use. Caller must have
816 // write lock.
817 func (fn *filenode) pruneMemSegments() {
818         // TODO: share code with (*dirnode)flush()
819         // TODO: pack/flush small blocks too, when fragmented
820         for idx, seg := range fn.segments {
821                 seg, ok := seg.(*memSegment)
822                 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
823                         continue
824                 }
825                 // Setting seg.flushing guarantees seg.buf will not be
826                 // modified in place: WriteAt and Truncate will
827                 // allocate a new buf instead, if necessary.
828                 idx, buf := idx, seg.buf
829                 done := make(chan struct{})
830                 seg.flushing = done
831                 // If lots of background writes are already in
832                 // progress, block here until one finishes, rather
833                 // than pile up an unlimited number of buffered writes
834                 // and network flush operations.
835                 fn.fs.throttle().Acquire()
836                 go func() {
837                         defer close(done)
838                         resp, err := fn.FS().BlockWrite(context.Background(), BlockWriteOptions{
839                                 Data:           buf,
840                                 Replicas:       fn.fs.replicas,
841                                 StorageClasses: fn.fs.storageClasses,
842                         })
843                         fn.fs.throttle().Release()
844                         fn.Lock()
845                         defer fn.Unlock()
846                         if seg.flushing != done {
847                                 // A new seg.buf has been allocated.
848                                 return
849                         }
850                         if err != nil {
851                                 // TODO: stall (or return errors from)
852                                 // subsequent writes until flushing
853                                 // starts to succeed.
854                                 return
855                         }
856                         if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
857                                 // Segment has been dropped/moved/resized.
858                                 return
859                         }
860                         fn.memsize -= int64(len(buf))
861                         fn.segments[idx] = storedSegment{
862                                 kc:      fn.FS(),
863                                 locator: resp.Locator,
864                                 size:    len(buf),
865                                 offset:  0,
866                                 length:  len(buf),
867                         }
868                 }()
869         }
870 }
871
872 // Block until all pending pruneMemSegments/flush work is
873 // finished. Caller must NOT have lock.
874 func (fn *filenode) waitPrune() {
875         var pending []<-chan struct{}
876         fn.Lock()
877         for _, seg := range fn.segments {
878                 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
879                         pending = append(pending, seg.flushing)
880                 }
881         }
882         fn.Unlock()
883         for _, p := range pending {
884                 <-p
885         }
886 }
887
888 func (fn *filenode) Snapshot() (inode, error) {
889         fn.RLock()
890         defer fn.RUnlock()
891         segments := make([]segment, 0, len(fn.segments))
892         for _, seg := range fn.segments {
893                 segments = append(segments, seg.Slice(0, seg.Len()))
894         }
895         return &filenode{
896                 fileinfo: fn.fileinfo,
897                 segments: segments,
898         }, nil
899 }
900
901 func (fn *filenode) Splice(repl inode) error {
902         repl, err := repl.Snapshot()
903         if err != nil {
904                 return err
905         }
906         fn.parent.Lock()
907         defer fn.parent.Unlock()
908         fn.Lock()
909         defer fn.Unlock()
910         _, err = fn.parent.Child(fn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
911         if err != nil {
912                 return err
913         }
914         switch repl := repl.(type) {
915         case *dirnode:
916                 repl.parent = fn.parent
917                 repl.fileinfo.name = fn.fileinfo.name
918                 repl.setTreeFS(fn.fs)
919         case *filenode:
920                 repl.parent = fn.parent
921                 repl.fileinfo.name = fn.fileinfo.name
922                 repl.fs = fn.fs
923         default:
924                 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
925         }
926         return nil
927 }
928
929 type dirnode struct {
930         fs *collectionFileSystem
931         treenode
932 }
933
934 func (dn *dirnode) FS() FileSystem {
935         return dn.fs
936 }
937
938 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
939         if dn == dn.fs.rootnode() && name == ".arvados#collection" {
940                 gn := &getternode{Getter: func() ([]byte, error) {
941                         var coll Collection
942                         var err error
943                         coll.ManifestText, err = dn.fs.MarshalManifest(".")
944                         if err != nil {
945                                 return nil, err
946                         }
947                         coll.UUID = dn.fs.uuid
948                         data, err := json.Marshal(&coll)
949                         if err == nil {
950                                 data = append(data, '\n')
951                         }
952                         return data, err
953                 }}
954                 gn.SetParent(dn, name)
955                 return gn, nil
956         }
957         if dn == dn.fs.rootnode() && name == ".arvados#collection_id" {
958                 gn := &getternode{Getter: func() ([]byte, error) {
959                         data, err := json.Marshal(Collection{UUID: dn.fs.uuid})
960                         if err == nil {
961                                 data = append(data, '\n')
962                         }
963                         return data, err
964                 }}
965                 gn.SetParent(dn, name)
966                 return gn, nil
967         }
968         return dn.treenode.Child(name, replace)
969 }
970
971 type fnSegmentRef struct {
972         fn  *filenode
973         idx int
974 }
975
976 // commitBlock concatenates the data from the given filenode segments
977 // (which must be *memSegments), writes the data out to Keep as a
978 // single block, and replaces the filenodes' *memSegments with
979 // storedSegments that reference the relevant portions of the new
980 // block.
981 //
982 // bufsize is the total data size in refs. It is used to preallocate
983 // the correct amount of memory when len(refs)>1.
984 //
985 // If sync is false, commitBlock returns right away, after starting a
986 // goroutine to do the writes, reacquire the filenodes' locks, and
987 // swap out the *memSegments. Some filenodes' segments might get
988 // modified/rearranged in the meantime, in which case commitBlock
989 // won't replace them.
990 //
991 // Caller must have write lock.
992 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
993         if len(refs) == 0 {
994                 return nil
995         }
996         if err := ctx.Err(); err != nil {
997                 return err
998         }
999         done := make(chan struct{})
1000         var block []byte
1001         segs := make([]*memSegment, 0, len(refs))
1002         offsets := make([]int, 0, len(refs)) // location of segment's data within block
1003         for _, ref := range refs {
1004                 seg := ref.fn.segments[ref.idx].(*memSegment)
1005                 if !sync && seg.flushingUnfinished() {
1006                         // Let the other flushing goroutine finish. If
1007                         // it fails, we'll try again next time.
1008                         close(done)
1009                         return nil
1010                 }
1011                 // In sync mode, we proceed regardless of
1012                 // whether another flush is in progress: It
1013                 // can't finish before we do, because we hold
1014                 // fn's lock until we finish our own writes.
1015                 seg.flushing = done
1016                 offsets = append(offsets, len(block))
1017                 if len(refs) == 1 {
1018                         block = seg.buf
1019                 } else if block == nil {
1020                         block = append(make([]byte, 0, bufsize), seg.buf...)
1021                 } else {
1022                         block = append(block, seg.buf...)
1023                 }
1024                 segs = append(segs, seg)
1025         }
1026         blocksize := len(block)
1027         dn.fs.throttle().Acquire()
1028         errs := make(chan error, 1)
1029         go func() {
1030                 defer close(done)
1031                 defer close(errs)
1032                 resp, err := dn.fs.BlockWrite(context.Background(), BlockWriteOptions{
1033                         Data:           block,
1034                         Replicas:       dn.fs.replicas,
1035                         StorageClasses: dn.fs.storageClasses,
1036                 })
1037                 dn.fs.throttle().Release()
1038                 if err != nil {
1039                         errs <- err
1040                         return
1041                 }
1042                 for idx, ref := range refs {
1043                         if !sync {
1044                                 ref.fn.Lock()
1045                                 // In async mode, fn's lock was
1046                                 // released while we were waiting for
1047                                 // PutB(); lots of things might have
1048                                 // changed.
1049                                 if len(ref.fn.segments) <= ref.idx {
1050                                         // file segments have
1051                                         // rearranged or changed in
1052                                         // some way
1053                                         ref.fn.Unlock()
1054                                         continue
1055                                 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
1056                                         // segment has been replaced
1057                                         ref.fn.Unlock()
1058                                         continue
1059                                 } else if seg.flushing != done {
1060                                         // seg.buf has been replaced
1061                                         ref.fn.Unlock()
1062                                         continue
1063                                 }
1064                         }
1065                         data := ref.fn.segments[ref.idx].(*memSegment).buf
1066                         ref.fn.segments[ref.idx] = storedSegment{
1067                                 kc:      dn.fs,
1068                                 locator: resp.Locator,
1069                                 size:    blocksize,
1070                                 offset:  offsets[idx],
1071                                 length:  len(data),
1072                         }
1073                         // atomic is needed here despite caller having
1074                         // lock: caller might be running concurrent
1075                         // commitBlock() goroutines using the same
1076                         // lock, writing different segments from the
1077                         // same file.
1078                         atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
1079                         if !sync {
1080                                 ref.fn.Unlock()
1081                         }
1082                 }
1083         }()
1084         if sync {
1085                 return <-errs
1086         }
1087         return nil
1088 }
1089
1090 type flushOpts struct {
1091         sync        bool
1092         shortBlocks bool
1093 }
1094
1095 // flush in-memory data and remote-cluster block references (for the
1096 // children with the given names, which must be children of dn) to
1097 // local-cluster persistent storage.
1098 //
1099 // Caller must have write lock on dn and the named children.
1100 //
1101 // If any children are dirs, they will be flushed recursively.
1102 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
1103         cg := newContextGroup(ctx)
1104         defer cg.Cancel()
1105
1106         goCommit := func(refs []fnSegmentRef, bufsize int) {
1107                 cg.Go(func() error {
1108                         return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
1109                 })
1110         }
1111
1112         var pending []fnSegmentRef
1113         var pendingLen int = 0
1114         localLocator := map[string]string{}
1115         for _, name := range names {
1116                 switch node := dn.inodes[name].(type) {
1117                 case *dirnode:
1118                         grandchildNames := node.sortedNames()
1119                         for _, grandchildName := range grandchildNames {
1120                                 grandchild := node.inodes[grandchildName]
1121                                 grandchild.Lock()
1122                                 defer grandchild.Unlock()
1123                         }
1124                         cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
1125                 case *filenode:
1126                         for idx, seg := range node.segments {
1127                                 switch seg := seg.(type) {
1128                                 case storedSegment:
1129                                         loc, ok := localLocator[seg.locator]
1130                                         if !ok {
1131                                                 var err error
1132                                                 loc, err = dn.fs.LocalLocator(seg.locator)
1133                                                 if err != nil {
1134                                                         return err
1135                                                 }
1136                                                 localLocator[seg.locator] = loc
1137                                         }
1138                                         seg.locator = loc
1139                                         node.segments[idx] = seg
1140                                 case *memSegment:
1141                                         if seg.Len() > maxBlockSize/2 {
1142                                                 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
1143                                                 continue
1144                                         }
1145                                         if pendingLen+seg.Len() > maxBlockSize {
1146                                                 goCommit(pending, pendingLen)
1147                                                 pending = nil
1148                                                 pendingLen = 0
1149                                         }
1150                                         pending = append(pending, fnSegmentRef{node, idx})
1151                                         pendingLen += seg.Len()
1152                                 default:
1153                                         panic(fmt.Sprintf("can't sync segment type %T", seg))
1154                                 }
1155                         }
1156                 }
1157         }
1158         if opts.shortBlocks {
1159                 goCommit(pending, pendingLen)
1160         }
1161         return cg.Wait()
1162 }
1163
1164 // caller must have write lock.
1165 func (dn *dirnode) MemorySize() (size int64) {
1166         for _, name := range dn.sortedNames() {
1167                 node := dn.inodes[name]
1168                 node.Lock()
1169                 defer node.Unlock()
1170                 switch node := node.(type) {
1171                 case *dirnode:
1172                         size += node.MemorySize()
1173                 case *filenode:
1174                         size += 64
1175                         for _, seg := range node.segments {
1176                                 switch seg := seg.(type) {
1177                                 case *memSegment:
1178                                         size += int64(seg.Len())
1179                                 }
1180                                 size += 64
1181                         }
1182                 }
1183         }
1184         return 64 + size
1185 }
1186
1187 // caller must have write lock.
1188 func (dn *dirnode) sortedNames() []string {
1189         names := make([]string, 0, len(dn.inodes))
1190         for name := range dn.inodes {
1191                 names = append(names, name)
1192         }
1193         sort.Strings(names)
1194         return names
1195 }
1196
1197 // caller must have write lock.
1198 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
1199         cg := newContextGroup(ctx)
1200         defer cg.Cancel()
1201
1202         if len(dn.inodes) == 0 {
1203                 if prefix == "." {
1204                         return "", nil
1205                 }
1206                 // Express the existence of an empty directory by
1207                 // adding an empty file named `\056`, which (unlike
1208                 // the more obvious spelling `.`) is accepted by the
1209                 // API's manifest validator.
1210                 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
1211         }
1212
1213         names := dn.sortedNames()
1214
1215         // Wait for children to finish any pending write operations
1216         // before locking them.
1217         for _, name := range names {
1218                 node := dn.inodes[name]
1219                 if fn, ok := node.(*filenode); ok {
1220                         fn.waitPrune()
1221                 }
1222         }
1223
1224         var dirnames []string
1225         var filenames []string
1226         for _, name := range names {
1227                 node := dn.inodes[name]
1228                 node.Lock()
1229                 defer node.Unlock()
1230                 switch node := node.(type) {
1231                 case *dirnode:
1232                         dirnames = append(dirnames, name)
1233                 case *filenode:
1234                         filenames = append(filenames, name)
1235                 default:
1236                         panic(fmt.Sprintf("can't marshal inode type %T", node))
1237                 }
1238         }
1239
1240         subdirs := make([]string, len(dirnames))
1241         rootdir := ""
1242         for i, name := range dirnames {
1243                 i, name := i, name
1244                 cg.Go(func() error {
1245                         txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
1246                         subdirs[i] = txt
1247                         return err
1248                 })
1249         }
1250
1251         cg.Go(func() error {
1252                 var streamLen int64
1253                 type filepart struct {
1254                         name   string
1255                         offset int64
1256                         length int64
1257                 }
1258
1259                 var fileparts []filepart
1260                 var blocks []string
1261                 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
1262                         return err
1263                 }
1264                 for _, name := range filenames {
1265                         node := dn.inodes[name].(*filenode)
1266                         if len(node.segments) == 0 {
1267                                 fileparts = append(fileparts, filepart{name: name})
1268                                 continue
1269                         }
1270                         for _, seg := range node.segments {
1271                                 switch seg := seg.(type) {
1272                                 case storedSegment:
1273                                         if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
1274                                                 streamLen -= int64(seg.size)
1275                                         } else {
1276                                                 blocks = append(blocks, seg.locator)
1277                                         }
1278                                         next := filepart{
1279                                                 name:   name,
1280                                                 offset: streamLen + int64(seg.offset),
1281                                                 length: int64(seg.length),
1282                                         }
1283                                         if prev := len(fileparts) - 1; prev >= 0 &&
1284                                                 fileparts[prev].name == name &&
1285                                                 fileparts[prev].offset+fileparts[prev].length == next.offset {
1286                                                 fileparts[prev].length += next.length
1287                                         } else {
1288                                                 fileparts = append(fileparts, next)
1289                                         }
1290                                         streamLen += int64(seg.size)
1291                                 default:
1292                                         // This can't happen: we
1293                                         // haven't unlocked since
1294                                         // calling flush(sync=true).
1295                                         panic(fmt.Sprintf("can't marshal segment type %T", seg))
1296                                 }
1297                         }
1298                 }
1299                 var filetokens []string
1300                 for _, s := range fileparts {
1301                         filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1302                 }
1303                 if len(filetokens) == 0 {
1304                         return nil
1305                 } else if len(blocks) == 0 {
1306                         blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1307                 }
1308                 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1309                 return nil
1310         })
1311         err := cg.Wait()
1312         return rootdir + strings.Join(subdirs, ""), err
1313 }
1314
1315 func (dn *dirnode) loadManifest(txt string) error {
1316         streams := bytes.Split([]byte(txt), []byte{'\n'})
1317         if len(streams[len(streams)-1]) != 0 {
1318                 return fmt.Errorf("line %d: no trailing newline", len(streams))
1319         }
1320         streams = streams[:len(streams)-1]
1321         segments := []storedSegment{}
1322         // To reduce allocs, we reuse a single "pathparts" slice
1323         // (pre-split on "/" separators) for the duration of this
1324         // func.
1325         var pathparts []string
1326         // To reduce allocs, we reuse a single "toks" slice of 3 byte
1327         // slices.
1328         var toks = make([][]byte, 3)
1329         // Similar to bytes.SplitN(token, []byte{c}, 3), but splits
1330         // into the toks slice rather than allocating a new one, and
1331         // returns the number of toks (1, 2, or 3).
1332         splitToToks := func(src []byte, c rune) int {
1333                 c1 := bytes.IndexRune(src, c)
1334                 if c1 < 0 {
1335                         toks[0] = src
1336                         return 1
1337                 }
1338                 toks[0], src = src[:c1], src[c1+1:]
1339                 c2 := bytes.IndexRune(src, c)
1340                 if c2 < 0 {
1341                         toks[1] = src
1342                         return 2
1343                 }
1344                 toks[1], toks[2] = src[:c2], src[c2+1:]
1345                 return 3
1346         }
1347         for i, stream := range streams {
1348                 lineno := i + 1
1349                 var anyFileTokens bool
1350                 var pos int64
1351                 var segIdx int
1352                 segments = segments[:0]
1353                 pathparts = nil
1354                 streamparts := 0
1355                 for i, token := range bytes.Split(stream, []byte{' '}) {
1356                         if i == 0 {
1357                                 pathparts = strings.Split(manifestUnescape(string(token)), "/")
1358                                 streamparts = len(pathparts)
1359                                 continue
1360                         }
1361                         if !bytes.ContainsRune(token, ':') {
1362                                 if anyFileTokens {
1363                                         return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1364                                 }
1365                                 if splitToToks(token, '+') < 2 {
1366                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1367                                 }
1368                                 length, err := strconv.ParseInt(string(toks[1]), 10, 32)
1369                                 if err != nil || length < 0 {
1370                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1371                                 }
1372                                 segments = append(segments, storedSegment{
1373                                         locator: string(token),
1374                                         size:    int(length),
1375                                         offset:  0,
1376                                         length:  int(length),
1377                                 })
1378                                 continue
1379                         } else if len(segments) == 0 {
1380                                 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1381                         }
1382                         if splitToToks(token, ':') != 3 {
1383                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1384                         }
1385                         anyFileTokens = true
1386
1387                         offset, err := strconv.ParseInt(string(toks[0]), 10, 64)
1388                         if err != nil || offset < 0 {
1389                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1390                         }
1391                         length, err := strconv.ParseInt(string(toks[1]), 10, 64)
1392                         if err != nil || length < 0 {
1393                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1394                         }
1395                         if !bytes.ContainsAny(toks[2], `\/`) {
1396                                 // optimization for a common case
1397                                 pathparts = append(pathparts[:streamparts], string(toks[2]))
1398                         } else {
1399                                 pathparts = append(pathparts[:streamparts], strings.Split(manifestUnescape(string(toks[2])), "/")...)
1400                         }
1401                         fnode, err := dn.createFileAndParents(pathparts)
1402                         if fnode == nil && err == nil && length == 0 {
1403                                 // Special case: an empty file used as
1404                                 // a marker to preserve an otherwise
1405                                 // empty directory in a manifest.
1406                                 continue
1407                         }
1408                         if err != nil || (fnode == nil && length != 0) {
1409                                 return fmt.Errorf("line %d: cannot use name %q with length %d: %s", lineno, toks[2], length, err)
1410                         }
1411                         // Map the stream offset/range coordinates to
1412                         // block/offset/range coordinates and add
1413                         // corresponding storedSegments to the filenode
1414                         if pos > offset {
1415                                 // Can't continue where we left off.
1416                                 // TODO: binary search instead of
1417                                 // rewinding all the way (but this
1418                                 // situation might be rare anyway)
1419                                 segIdx, pos = 0, 0
1420                         }
1421                         for ; segIdx < len(segments); segIdx++ {
1422                                 seg := segments[segIdx]
1423                                 next := pos + int64(seg.Len())
1424                                 if next <= offset || seg.Len() == 0 {
1425                                         pos = next
1426                                         continue
1427                                 }
1428                                 if pos >= offset+length {
1429                                         break
1430                                 }
1431                                 var blkOff int
1432                                 if pos < offset {
1433                                         blkOff = int(offset - pos)
1434                                 }
1435                                 blkLen := seg.Len() - blkOff
1436                                 if pos+int64(blkOff+blkLen) > offset+length {
1437                                         blkLen = int(offset + length - pos - int64(blkOff))
1438                                 }
1439                                 fnode.appendSegment(storedSegment{
1440                                         kc:      dn.fs,
1441                                         locator: seg.locator,
1442                                         size:    seg.size,
1443                                         offset:  blkOff,
1444                                         length:  blkLen,
1445                                 })
1446                                 if next > offset+length {
1447                                         break
1448                                 } else {
1449                                         pos = next
1450                                 }
1451                         }
1452                         if segIdx == len(segments) && pos < offset+length {
1453                                 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1454                         }
1455                 }
1456                 if !anyFileTokens {
1457                         return fmt.Errorf("line %d: no file segments", lineno)
1458                 } else if len(segments) == 0 {
1459                         return fmt.Errorf("line %d: no locators", lineno)
1460                 } else if streamparts == 0 {
1461                         return fmt.Errorf("line %d: no stream name", lineno)
1462                 }
1463         }
1464         return nil
1465 }
1466
1467 // only safe to call from loadManifest -- no locking.
1468 //
1469 // If path is a "parent directory exists" marker (the last path
1470 // component is "."), the returned values are both nil.
1471 //
1472 // Newly added nodes have modtime==0. Caller is responsible for fixing
1473 // them with backdateTree.
1474 func (dn *dirnode) createFileAndParents(names []string) (fn *filenode, err error) {
1475         var node inode = dn
1476         basename := names[len(names)-1]
1477         for _, name := range names[:len(names)-1] {
1478                 switch name {
1479                 case "", ".":
1480                         continue
1481                 case "..":
1482                         if node == dn {
1483                                 // can't be sure parent will be a *dirnode
1484                                 return nil, ErrInvalidArgument
1485                         }
1486                         node = node.Parent()
1487                         continue
1488                 }
1489                 node.Lock()
1490                 unlock := node.Unlock
1491                 node, err = node.Child(name, func(child inode) (inode, error) {
1492                         if child == nil {
1493                                 // note modtime will be fixed later in backdateTree()
1494                                 child, err := node.FS().newNode(name, 0755|os.ModeDir, time.Time{})
1495                                 if err != nil {
1496                                         return nil, err
1497                                 }
1498                                 child.SetParent(node, name)
1499                                 return child, nil
1500                         } else if !child.IsDir() {
1501                                 return child, ErrFileExists
1502                         } else {
1503                                 return child, nil
1504                         }
1505                 })
1506                 unlock()
1507                 if err != nil {
1508                         return
1509                 }
1510         }
1511         if basename == "." {
1512                 return
1513         } else if !permittedName(basename) {
1514                 err = fmt.Errorf("invalid file part %q in path %q", basename, names)
1515                 return
1516         }
1517         node.Lock()
1518         defer node.Unlock()
1519         _, err = node.Child(basename, func(child inode) (inode, error) {
1520                 switch child := child.(type) {
1521                 case nil:
1522                         child, err = node.FS().newNode(basename, 0755, time.Time{})
1523                         if err != nil {
1524                                 return nil, err
1525                         }
1526                         child.SetParent(node, basename)
1527                         fn = child.(*filenode)
1528                         return child, nil
1529                 case *filenode:
1530                         fn = child
1531                         return child, nil
1532                 case *dirnode:
1533                         return child, ErrIsDirectory
1534                 default:
1535                         return child, ErrInvalidArgument
1536                 }
1537         })
1538         return
1539 }
1540
1541 func (dn *dirnode) TreeSize() (bytes int64) {
1542         dn.RLock()
1543         defer dn.RUnlock()
1544         for _, i := range dn.inodes {
1545                 switch i := i.(type) {
1546                 case *filenode:
1547                         bytes += i.Size()
1548                 case *dirnode:
1549                         bytes += i.TreeSize()
1550                 }
1551         }
1552         return
1553 }
1554
1555 func (dn *dirnode) Snapshot() (inode, error) {
1556         return dn.snapshot()
1557 }
1558
1559 func (dn *dirnode) snapshot() (*dirnode, error) {
1560         dn.RLock()
1561         defer dn.RUnlock()
1562         snap := &dirnode{
1563                 treenode: treenode{
1564                         inodes:   make(map[string]inode, len(dn.inodes)),
1565                         fileinfo: dn.fileinfo,
1566                 },
1567         }
1568         for name, child := range dn.inodes {
1569                 dupchild, err := child.Snapshot()
1570                 if err != nil {
1571                         return nil, err
1572                 }
1573                 snap.inodes[name] = dupchild
1574                 dupchild.SetParent(snap, name)
1575         }
1576         return snap, nil
1577 }
1578
1579 func (dn *dirnode) Splice(repl inode) error {
1580         repl, err := repl.Snapshot()
1581         if err != nil {
1582                 return fmt.Errorf("cannot copy snapshot: %w", err)
1583         }
1584         switch repl := repl.(type) {
1585         default:
1586                 return fmt.Errorf("cannot splice snapshot containing %T: %w", repl, ErrInvalidArgument)
1587         case *dirnode:
1588                 dn.Lock()
1589                 defer dn.Unlock()
1590                 dn.inodes = repl.inodes
1591                 dn.setTreeFS(dn.fs)
1592         case *filenode:
1593                 dn.parent.Lock()
1594                 defer dn.parent.Unlock()
1595                 removing, err := dn.parent.Child(dn.fileinfo.name, nil)
1596                 if err != nil {
1597                         return fmt.Errorf("cannot use Splice to replace a top-level directory with a file: %w", ErrInvalidOperation)
1598                 } else if removing != dn {
1599                         // If ../thisdirname is not this dirnode, it
1600                         // must be an inode that wraps a dirnode, like
1601                         // a collectionFileSystem or deferrednode.
1602                         if deferred, ok := removing.(*deferrednode); ok {
1603                                 // More useful to report the type of
1604                                 // the wrapped node rather than just
1605                                 // *deferrednode. (We know the real
1606                                 // inode is already loaded because dn
1607                                 // is inside it.)
1608                                 removing = deferred.realinode()
1609                         }
1610                         return fmt.Errorf("cannot use Splice to attach a file at top level of %T: %w", removing, ErrInvalidOperation)
1611                 }
1612                 dn.Lock()
1613                 defer dn.Unlock()
1614                 _, err = dn.parent.Child(dn.fileinfo.name, func(inode) (inode, error) { return repl, nil })
1615                 if err != nil {
1616                         return fmt.Errorf("error replacing filenode: dn.parent.Child(): %w", err)
1617                 }
1618                 repl.fs = dn.fs
1619         }
1620         return nil
1621 }
1622
1623 func (dn *dirnode) setTreeFS(fs *collectionFileSystem) {
1624         dn.fs = fs
1625         for _, child := range dn.inodes {
1626                 switch child := child.(type) {
1627                 case *dirnode:
1628                         child.setTreeFS(fs)
1629                 case *filenode:
1630                         child.fs = fs
1631                 }
1632         }
1633 }
1634
1635 type segment interface {
1636         io.ReaderAt
1637         Len() int
1638         // Return a new segment with a subsection of the data from this
1639         // one. length<0 means length=Len()-off.
1640         Slice(off int, length int) segment
1641 }
1642
1643 type memSegment struct {
1644         buf []byte
1645         // If flushing is not nil and not ready/closed, then a) buf is
1646         // being shared by a pruneMemSegments goroutine, and must be
1647         // copied on write; and b) the flushing channel will close
1648         // when the goroutine finishes, whether it succeeds or not.
1649         flushing <-chan struct{}
1650 }
1651
1652 func (me *memSegment) flushingUnfinished() bool {
1653         if me.flushing == nil {
1654                 return false
1655         }
1656         select {
1657         case <-me.flushing:
1658                 me.flushing = nil
1659                 return false
1660         default:
1661                 return true
1662         }
1663 }
1664
1665 func (me *memSegment) Len() int {
1666         return len(me.buf)
1667 }
1668
1669 func (me *memSegment) Slice(off, length int) segment {
1670         if length < 0 {
1671                 length = len(me.buf) - off
1672         }
1673         buf := make([]byte, length)
1674         copy(buf, me.buf[off:])
1675         return &memSegment{buf: buf}
1676 }
1677
1678 func (me *memSegment) Truncate(n int) {
1679         if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1680                 newsize := 1024
1681                 for newsize < n {
1682                         newsize = newsize << 2
1683                 }
1684                 newbuf := make([]byte, n, newsize)
1685                 copy(newbuf, me.buf)
1686                 me.buf, me.flushing = newbuf, nil
1687         } else {
1688                 // reclaim existing capacity, and zero reclaimed part
1689                 oldlen := len(me.buf)
1690                 me.buf = me.buf[:n]
1691                 for i := oldlen; i < n; i++ {
1692                         me.buf[i] = 0
1693                 }
1694         }
1695 }
1696
1697 func (me *memSegment) WriteAt(p []byte, off int) {
1698         if off+len(p) > len(me.buf) {
1699                 panic("overflowed segment")
1700         }
1701         if me.flushing != nil {
1702                 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1703         }
1704         copy(me.buf[off:], p)
1705 }
1706
1707 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1708         if off > int64(me.Len()) {
1709                 err = io.EOF
1710                 return
1711         }
1712         n = copy(p, me.buf[int(off):])
1713         if n < len(p) {
1714                 err = io.EOF
1715         }
1716         return
1717 }
1718
1719 type storedSegment struct {
1720         kc      fsBackend
1721         locator string
1722         size    int // size of stored block (also encoded in locator)
1723         offset  int // position of segment within the stored block
1724         length  int // bytes in this segment (offset + length <= size)
1725 }
1726
1727 func (se storedSegment) Len() int {
1728         return se.length
1729 }
1730
1731 func (se storedSegment) Slice(n, size int) segment {
1732         se.offset += n
1733         se.length -= n
1734         if size >= 0 && se.length > size {
1735                 se.length = size
1736         }
1737         return se
1738 }
1739
1740 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1741         if off > int64(se.length) {
1742                 return 0, io.EOF
1743         }
1744         maxlen := se.length - int(off)
1745         if len(p) > maxlen {
1746                 p = p[:maxlen]
1747                 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1748                 if err == nil {
1749                         err = io.EOF
1750                 }
1751                 return
1752         }
1753         return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1754 }
1755
1756 func canonicalName(name string) string {
1757         name = path.Clean("/" + name)
1758         if name == "/" || name == "./" {
1759                 name = "."
1760         } else if strings.HasPrefix(name, "/") {
1761                 name = "." + name
1762         }
1763         return name
1764 }
1765
1766 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1767
1768 func manifestUnescapeFunc(seq string) string {
1769         if seq == `\\` {
1770                 return `\`
1771         }
1772         i, err := strconv.ParseUint(seq[1:], 8, 8)
1773         if err != nil {
1774                 // Invalid escape sequence: can't unescape.
1775                 return seq
1776         }
1777         return string([]byte{byte(i)})
1778 }
1779
1780 func manifestUnescape(s string) string {
1781         return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1782 }
1783
1784 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1785
1786 func manifestEscapeFunc(seq string) string {
1787         return fmt.Sprintf("\\%03o", byte(seq[0]))
1788 }
1789
1790 func manifestEscape(s string) string {
1791         return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)
1792 }