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