17841: Merge branch 'main' into 17841-add-duration
[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         "context"
9         "encoding/json"
10         "fmt"
11         "io"
12         "os"
13         "path"
14         "regexp"
15         "sort"
16         "strconv"
17         "strings"
18         "sync"
19         "sync/atomic"
20         "time"
21 )
22
23 var (
24         maxBlockSize      = 1 << 26
25         concurrentWriters = 4 // max goroutines writing to Keep in background and during flush()
26 )
27
28 // A CollectionFileSystem is a FileSystem that can be serialized as a
29 // manifest and stored as a collection.
30 type CollectionFileSystem interface {
31         FileSystem
32
33         // Flush all file data to Keep and return a snapshot of the
34         // filesystem suitable for saving as (Collection)ManifestText.
35         // Prefix (normally ".") is a top level directory, effectively
36         // prepended to all paths in the returned manifest.
37         MarshalManifest(prefix string) (string, error)
38
39         // Total data bytes in all files.
40         Size() int64
41 }
42
43 type collectionFileSystem struct {
44         fileSystem
45         uuid string
46 }
47
48 // FileSystem returns a CollectionFileSystem for the collection.
49 func (c *Collection) FileSystem(client apiClient, kc keepClient) (CollectionFileSystem, error) {
50         modTime := c.ModifiedAt
51         if modTime.IsZero() {
52                 modTime = time.Now()
53         }
54         fs := &collectionFileSystem{
55                 uuid: c.UUID,
56                 fileSystem: fileSystem{
57                         fsBackend: keepBackend{apiClient: client, keepClient: kc},
58                         thr:       newThrottle(concurrentWriters),
59                 },
60         }
61         root := &dirnode{
62                 fs: fs,
63                 treenode: treenode{
64                         fileinfo: fileinfo{
65                                 name:    ".",
66                                 mode:    os.ModeDir | 0755,
67                                 modTime: modTime,
68                         },
69                         inodes: make(map[string]inode),
70                 },
71         }
72         root.SetParent(root, ".")
73         if err := root.loadManifest(c.ManifestText); err != nil {
74                 return nil, err
75         }
76         backdateTree(root, modTime)
77         fs.root = root
78         return fs, nil
79 }
80
81 func backdateTree(n inode, modTime time.Time) {
82         switch n := n.(type) {
83         case *filenode:
84                 n.fileinfo.modTime = modTime
85         case *dirnode:
86                 n.fileinfo.modTime = modTime
87                 for _, n := range n.inodes {
88                         backdateTree(n, modTime)
89                 }
90         }
91 }
92
93 func (fs *collectionFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
94         if name == "" || name == "." || name == ".." {
95                 return nil, ErrInvalidArgument
96         }
97         if perm.IsDir() {
98                 return &dirnode{
99                         fs: fs,
100                         treenode: treenode{
101                                 fileinfo: fileinfo{
102                                         name:    name,
103                                         mode:    perm | os.ModeDir,
104                                         modTime: modTime,
105                                 },
106                                 inodes: make(map[string]inode),
107                         },
108                 }, nil
109         }
110         return &filenode{
111                 fs: fs,
112                 fileinfo: fileinfo{
113                         name:    name,
114                         mode:    perm & ^os.ModeDir,
115                         modTime: modTime,
116                 },
117         }, nil
118 }
119
120 func (fs *collectionFileSystem) Child(name string, replace func(inode) (inode, error)) (inode, error) {
121         return fs.rootnode().Child(name, replace)
122 }
123
124 func (fs *collectionFileSystem) FS() FileSystem {
125         return fs
126 }
127
128 func (fs *collectionFileSystem) FileInfo() os.FileInfo {
129         return fs.rootnode().FileInfo()
130 }
131
132 func (fs *collectionFileSystem) IsDir() bool {
133         return true
134 }
135
136 func (fs *collectionFileSystem) Lock() {
137         fs.rootnode().Lock()
138 }
139
140 func (fs *collectionFileSystem) Unlock() {
141         fs.rootnode().Unlock()
142 }
143
144 func (fs *collectionFileSystem) RLock() {
145         fs.rootnode().RLock()
146 }
147
148 func (fs *collectionFileSystem) RUnlock() {
149         fs.rootnode().RUnlock()
150 }
151
152 func (fs *collectionFileSystem) Parent() inode {
153         return fs.rootnode().Parent()
154 }
155
156 func (fs *collectionFileSystem) Read(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
157         return 0, ptr, ErrInvalidOperation
158 }
159
160 func (fs *collectionFileSystem) Write(_ []byte, ptr filenodePtr) (int, filenodePtr, error) {
161         return 0, ptr, ErrInvalidOperation
162 }
163
164 func (fs *collectionFileSystem) Readdir() ([]os.FileInfo, error) {
165         return fs.rootnode().Readdir()
166 }
167
168 func (fs *collectionFileSystem) SetParent(parent inode, name string) {
169         fs.rootnode().SetParent(parent, name)
170 }
171
172 func (fs *collectionFileSystem) Truncate(int64) error {
173         return ErrInvalidOperation
174 }
175
176 func (fs *collectionFileSystem) Sync() error {
177         if fs.uuid == "" {
178                 return nil
179         }
180         txt, err := fs.MarshalManifest(".")
181         if err != nil {
182                 return fmt.Errorf("sync failed: %s", err)
183         }
184         coll := &Collection{
185                 UUID:         fs.uuid,
186                 ManifestText: txt,
187         }
188         err = fs.RequestAndDecode(nil, "PUT", "arvados/v1/collections/"+fs.uuid, nil, map[string]interface{}{
189                 "collection": map[string]string{
190                         "manifest_text": coll.ManifestText,
191                 },
192                 "select": []string{"uuid"},
193         })
194         if err != nil {
195                 return fmt.Errorf("sync failed: update %s: %s", fs.uuid, err)
196         }
197         return nil
198 }
199
200 func (fs *collectionFileSystem) Flush(path string, shortBlocks bool) error {
201         node, err := rlookup(fs.fileSystem.root, path)
202         if err != nil {
203                 return err
204         }
205         dn, ok := node.(*dirnode)
206         if !ok {
207                 return ErrNotADirectory
208         }
209         dn.Lock()
210         defer dn.Unlock()
211         names := dn.sortedNames()
212         if path != "" {
213                 // Caller only wants to flush the specified dir,
214                 // non-recursively.  Drop subdirs from the list of
215                 // names.
216                 var filenames []string
217                 for _, name := range names {
218                         if _, ok := dn.inodes[name].(*filenode); ok {
219                                 filenames = append(filenames, name)
220                         }
221                 }
222                 names = filenames
223         }
224         for _, name := range names {
225                 child := dn.inodes[name]
226                 child.Lock()
227                 defer child.Unlock()
228         }
229         return dn.flush(context.TODO(), names, flushOpts{sync: false, shortBlocks: shortBlocks})
230 }
231
232 func (fs *collectionFileSystem) MemorySize() int64 {
233         fs.fileSystem.root.Lock()
234         defer fs.fileSystem.root.Unlock()
235         return fs.fileSystem.root.(*dirnode).MemorySize()
236 }
237
238 func (fs *collectionFileSystem) MarshalManifest(prefix string) (string, error) {
239         fs.fileSystem.root.Lock()
240         defer fs.fileSystem.root.Unlock()
241         return fs.fileSystem.root.(*dirnode).marshalManifest(context.TODO(), prefix)
242 }
243
244 func (fs *collectionFileSystem) Size() int64 {
245         return fs.fileSystem.root.(*dirnode).TreeSize()
246 }
247
248 // filenodePtr is an offset into a file that is (usually) efficient to
249 // seek to. Specifically, if filenode.repacked==filenodePtr.repacked
250 // then
251 // filenode.segments[filenodePtr.segmentIdx][filenodePtr.segmentOff]
252 // corresponds to file offset filenodePtr.off. Otherwise, it is
253 // necessary to reexamine len(filenode.segments[0]) etc. to find the
254 // correct segment and offset.
255 type filenodePtr struct {
256         off        int64
257         segmentIdx int
258         segmentOff int
259         repacked   int64
260 }
261
262 // seek returns a ptr that is consistent with both startPtr.off and
263 // the current state of fn. The caller must already hold fn.RLock() or
264 // fn.Lock().
265 //
266 // If startPtr is beyond EOF, ptr.segment* will indicate precisely
267 // EOF.
268 //
269 // After seeking:
270 //
271 //     ptr.segmentIdx == len(filenode.segments) // i.e., at EOF
272 //     ||
273 //     filenode.segments[ptr.segmentIdx].Len() > ptr.segmentOff
274 func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
275         ptr = startPtr
276         if ptr.off < 0 {
277                 // meaningless anyway
278                 return
279         } else if ptr.off >= fn.fileinfo.size {
280                 ptr.segmentIdx = len(fn.segments)
281                 ptr.segmentOff = 0
282                 ptr.repacked = fn.repacked
283                 return
284         } else if ptr.repacked == fn.repacked {
285                 // segmentIdx and segmentOff accurately reflect
286                 // ptr.off, but might have fallen off the end of a
287                 // segment
288                 if ptr.segmentOff >= fn.segments[ptr.segmentIdx].Len() {
289                         ptr.segmentIdx++
290                         ptr.segmentOff = 0
291                 }
292                 return
293         }
294         defer func() {
295                 ptr.repacked = fn.repacked
296         }()
297         if ptr.off >= fn.fileinfo.size {
298                 ptr.segmentIdx, ptr.segmentOff = len(fn.segments), 0
299                 return
300         }
301         // Recompute segmentIdx and segmentOff.  We have already
302         // established fn.fileinfo.size > ptr.off >= 0, so we don't
303         // have to deal with edge cases here.
304         var off int64
305         for ptr.segmentIdx, ptr.segmentOff = 0, 0; off < ptr.off; ptr.segmentIdx++ {
306                 // This would panic (index out of range) if
307                 // fn.fileinfo.size were larger than
308                 // sum(fn.segments[i].Len()) -- but that can't happen
309                 // because we have ensured fn.fileinfo.size is always
310                 // accurate.
311                 segLen := int64(fn.segments[ptr.segmentIdx].Len())
312                 if off+segLen > ptr.off {
313                         ptr.segmentOff = int(ptr.off - off)
314                         break
315                 }
316                 off += segLen
317         }
318         return
319 }
320
321 // filenode implements inode.
322 type filenode struct {
323         parent   inode
324         fs       FileSystem
325         fileinfo fileinfo
326         segments []segment
327         // number of times `segments` has changed in a
328         // way that might invalidate a filenodePtr
329         repacked int64
330         memsize  int64 // bytes in memSegments
331         sync.RWMutex
332         nullnode
333 }
334
335 // caller must have lock
336 func (fn *filenode) appendSegment(e segment) {
337         fn.segments = append(fn.segments, e)
338         fn.fileinfo.size += int64(e.Len())
339 }
340
341 func (fn *filenode) SetParent(p inode, name string) {
342         fn.Lock()
343         defer fn.Unlock()
344         fn.parent = p
345         fn.fileinfo.name = name
346 }
347
348 func (fn *filenode) Parent() inode {
349         fn.RLock()
350         defer fn.RUnlock()
351         return fn.parent
352 }
353
354 func (fn *filenode) FS() FileSystem {
355         return fn.fs
356 }
357
358 // Read reads file data from a single segment, starting at startPtr,
359 // into p. startPtr is assumed not to be up-to-date. Caller must have
360 // RLock or Lock.
361 func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
362         ptr = fn.seek(startPtr)
363         if ptr.off < 0 {
364                 err = ErrNegativeOffset
365                 return
366         }
367         if ptr.segmentIdx >= len(fn.segments) {
368                 err = io.EOF
369                 return
370         }
371         n, err = fn.segments[ptr.segmentIdx].ReadAt(p, int64(ptr.segmentOff))
372         if n > 0 {
373                 ptr.off += int64(n)
374                 ptr.segmentOff += n
375                 if ptr.segmentOff == fn.segments[ptr.segmentIdx].Len() {
376                         ptr.segmentIdx++
377                         ptr.segmentOff = 0
378                         if ptr.segmentIdx < len(fn.segments) && err == io.EOF {
379                                 err = nil
380                         }
381                 }
382         }
383         return
384 }
385
386 func (fn *filenode) Size() int64 {
387         fn.RLock()
388         defer fn.RUnlock()
389         return fn.fileinfo.Size()
390 }
391
392 func (fn *filenode) FileInfo() os.FileInfo {
393         fn.RLock()
394         defer fn.RUnlock()
395         return fn.fileinfo
396 }
397
398 func (fn *filenode) Truncate(size int64) error {
399         fn.Lock()
400         defer fn.Unlock()
401         return fn.truncate(size)
402 }
403
404 func (fn *filenode) truncate(size int64) error {
405         if size == fn.fileinfo.size {
406                 return nil
407         }
408         fn.repacked++
409         if size < fn.fileinfo.size {
410                 ptr := fn.seek(filenodePtr{off: size})
411                 for i := ptr.segmentIdx; i < len(fn.segments); i++ {
412                         if seg, ok := fn.segments[i].(*memSegment); ok {
413                                 fn.memsize -= int64(seg.Len())
414                         }
415                 }
416                 if ptr.segmentOff == 0 {
417                         fn.segments = fn.segments[:ptr.segmentIdx]
418                 } else {
419                         fn.segments = fn.segments[:ptr.segmentIdx+1]
420                         switch seg := fn.segments[ptr.segmentIdx].(type) {
421                         case *memSegment:
422                                 seg.Truncate(ptr.segmentOff)
423                                 fn.memsize += int64(seg.Len())
424                         default:
425                                 fn.segments[ptr.segmentIdx] = seg.Slice(0, ptr.segmentOff)
426                         }
427                 }
428                 fn.fileinfo.size = size
429                 return nil
430         }
431         for size > fn.fileinfo.size {
432                 grow := size - fn.fileinfo.size
433                 var seg *memSegment
434                 var ok bool
435                 if len(fn.segments) == 0 {
436                         seg = &memSegment{}
437                         fn.segments = append(fn.segments, seg)
438                 } else if seg, ok = fn.segments[len(fn.segments)-1].(*memSegment); !ok || seg.Len() >= maxBlockSize {
439                         seg = &memSegment{}
440                         fn.segments = append(fn.segments, seg)
441                 }
442                 if maxgrow := int64(maxBlockSize - seg.Len()); maxgrow < grow {
443                         grow = maxgrow
444                 }
445                 seg.Truncate(seg.Len() + int(grow))
446                 fn.fileinfo.size += grow
447                 fn.memsize += grow
448         }
449         return nil
450 }
451
452 // Write writes data from p to the file, starting at startPtr,
453 // extending the file size if necessary. Caller must have Lock.
454 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
455         if startPtr.off > fn.fileinfo.size {
456                 if err = fn.truncate(startPtr.off); err != nil {
457                         return 0, startPtr, err
458                 }
459         }
460         ptr = fn.seek(startPtr)
461         if ptr.off < 0 {
462                 err = ErrNegativeOffset
463                 return
464         }
465         for len(p) > 0 && err == nil {
466                 cando := p
467                 if len(cando) > maxBlockSize {
468                         cando = cando[:maxBlockSize]
469                 }
470                 // Rearrange/grow fn.segments (and shrink cando if
471                 // needed) such that cando can be copied to
472                 // fn.segments[ptr.segmentIdx] at offset
473                 // ptr.segmentOff.
474                 cur := ptr.segmentIdx
475                 prev := ptr.segmentIdx - 1
476                 var curWritable bool
477                 if cur < len(fn.segments) {
478                         _, curWritable = fn.segments[cur].(*memSegment)
479                 }
480                 var prevAppendable bool
481                 if prev >= 0 && fn.segments[prev].Len() < maxBlockSize {
482                         _, prevAppendable = fn.segments[prev].(*memSegment)
483                 }
484                 if ptr.segmentOff > 0 && !curWritable {
485                         // Split a non-writable block.
486                         if max := fn.segments[cur].Len() - ptr.segmentOff; max <= len(cando) {
487                                 // Truncate cur, and insert a new
488                                 // segment after it.
489                                 cando = cando[:max]
490                                 fn.segments = append(fn.segments, nil)
491                                 copy(fn.segments[cur+1:], fn.segments[cur:])
492                         } else {
493                                 // Split cur into two copies, truncate
494                                 // the one on the left, shift the one
495                                 // on the right, and insert a new
496                                 // segment between them.
497                                 fn.segments = append(fn.segments, nil, nil)
498                                 copy(fn.segments[cur+2:], fn.segments[cur:])
499                                 fn.segments[cur+2] = fn.segments[cur+2].Slice(ptr.segmentOff+len(cando), -1)
500                         }
501                         cur++
502                         prev++
503                         seg := &memSegment{}
504                         seg.Truncate(len(cando))
505                         fn.memsize += int64(len(cando))
506                         fn.segments[cur] = seg
507                         fn.segments[prev] = fn.segments[prev].Slice(0, ptr.segmentOff)
508                         ptr.segmentIdx++
509                         ptr.segmentOff = 0
510                         fn.repacked++
511                         ptr.repacked++
512                 } else if curWritable {
513                         if fit := int(fn.segments[cur].Len()) - ptr.segmentOff; fit < len(cando) {
514                                 cando = cando[:fit]
515                         }
516                 } else {
517                         if prevAppendable {
518                                 // Shrink cando if needed to fit in
519                                 // prev segment.
520                                 if cangrow := maxBlockSize - fn.segments[prev].Len(); cangrow < len(cando) {
521                                         cando = cando[:cangrow]
522                                 }
523                         }
524
525                         if cur == len(fn.segments) {
526                                 // ptr is at EOF, filesize is changing.
527                                 fn.fileinfo.size += int64(len(cando))
528                         } else if el := fn.segments[cur].Len(); el <= len(cando) {
529                                 // cando is long enough that we won't
530                                 // need cur any more. shrink cando to
531                                 // be exactly as long as cur
532                                 // (otherwise we'd accidentally shift
533                                 // the effective position of all
534                                 // segments after cur).
535                                 cando = cando[:el]
536                                 copy(fn.segments[cur:], fn.segments[cur+1:])
537                                 fn.segments = fn.segments[:len(fn.segments)-1]
538                         } else {
539                                 // shrink cur by the same #bytes we're growing prev
540                                 fn.segments[cur] = fn.segments[cur].Slice(len(cando), -1)
541                         }
542
543                         if prevAppendable {
544                                 // Grow prev.
545                                 ptr.segmentIdx--
546                                 ptr.segmentOff = fn.segments[prev].Len()
547                                 fn.segments[prev].(*memSegment).Truncate(ptr.segmentOff + len(cando))
548                                 fn.memsize += int64(len(cando))
549                                 ptr.repacked++
550                                 fn.repacked++
551                         } else {
552                                 // Insert a segment between prev and
553                                 // cur, and advance prev/cur.
554                                 fn.segments = append(fn.segments, nil)
555                                 if cur < len(fn.segments) {
556                                         copy(fn.segments[cur+1:], fn.segments[cur:])
557                                         ptr.repacked++
558                                         fn.repacked++
559                                 } else {
560                                         // appending a new segment does
561                                         // not invalidate any ptrs
562                                 }
563                                 seg := &memSegment{}
564                                 seg.Truncate(len(cando))
565                                 fn.memsize += int64(len(cando))
566                                 fn.segments[cur] = seg
567                         }
568                 }
569
570                 // Finally we can copy bytes from cando to the current segment.
571                 fn.segments[ptr.segmentIdx].(*memSegment).WriteAt(cando, ptr.segmentOff)
572                 n += len(cando)
573                 p = p[len(cando):]
574
575                 ptr.off += int64(len(cando))
576                 ptr.segmentOff += len(cando)
577                 if ptr.segmentOff >= maxBlockSize {
578                         fn.pruneMemSegments()
579                 }
580                 if fn.segments[ptr.segmentIdx].Len() == ptr.segmentOff {
581                         ptr.segmentOff = 0
582                         ptr.segmentIdx++
583                 }
584
585                 fn.fileinfo.modTime = time.Now()
586         }
587         return
588 }
589
590 // Write some data out to disk to reduce memory use. Caller must have
591 // write lock.
592 func (fn *filenode) pruneMemSegments() {
593         // TODO: share code with (*dirnode)flush()
594         // TODO: pack/flush small blocks too, when fragmented
595         for idx, seg := range fn.segments {
596                 seg, ok := seg.(*memSegment)
597                 if !ok || seg.Len() < maxBlockSize || seg.flushing != nil {
598                         continue
599                 }
600                 // Setting seg.flushing guarantees seg.buf will not be
601                 // modified in place: WriteAt and Truncate will
602                 // allocate a new buf instead, if necessary.
603                 idx, buf := idx, seg.buf
604                 done := make(chan struct{})
605                 seg.flushing = done
606                 // If lots of background writes are already in
607                 // progress, block here until one finishes, rather
608                 // than pile up an unlimited number of buffered writes
609                 // and network flush operations.
610                 fn.fs.throttle().Acquire()
611                 go func() {
612                         defer close(done)
613                         locator, _, err := fn.FS().PutB(buf)
614                         fn.fs.throttle().Release()
615                         fn.Lock()
616                         defer fn.Unlock()
617                         if seg.flushing != done {
618                                 // A new seg.buf has been allocated.
619                                 return
620                         }
621                         if err != nil {
622                                 // TODO: stall (or return errors from)
623                                 // subsequent writes until flushing
624                                 // starts to succeed.
625                                 return
626                         }
627                         if len(fn.segments) <= idx || fn.segments[idx] != seg || len(seg.buf) != len(buf) {
628                                 // Segment has been dropped/moved/resized.
629                                 return
630                         }
631                         fn.memsize -= int64(len(buf))
632                         fn.segments[idx] = storedSegment{
633                                 kc:      fn.FS(),
634                                 locator: locator,
635                                 size:    len(buf),
636                                 offset:  0,
637                                 length:  len(buf),
638                         }
639                 }()
640         }
641 }
642
643 // Block until all pending pruneMemSegments/flush work is
644 // finished. Caller must NOT have lock.
645 func (fn *filenode) waitPrune() {
646         var pending []<-chan struct{}
647         fn.Lock()
648         for _, seg := range fn.segments {
649                 if seg, ok := seg.(*memSegment); ok && seg.flushing != nil {
650                         pending = append(pending, seg.flushing)
651                 }
652         }
653         fn.Unlock()
654         for _, p := range pending {
655                 <-p
656         }
657 }
658
659 type dirnode struct {
660         fs *collectionFileSystem
661         treenode
662 }
663
664 func (dn *dirnode) FS() FileSystem {
665         return dn.fs
666 }
667
668 func (dn *dirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
669         if dn == dn.fs.rootnode() && name == ".arvados#collection" {
670                 gn := &getternode{Getter: func() ([]byte, error) {
671                         var coll Collection
672                         var err error
673                         coll.ManifestText, err = dn.fs.MarshalManifest(".")
674                         if err != nil {
675                                 return nil, err
676                         }
677                         coll.UUID = dn.fs.uuid
678                         data, err := json.Marshal(&coll)
679                         if err == nil {
680                                 data = append(data, '\n')
681                         }
682                         return data, err
683                 }}
684                 gn.SetParent(dn, name)
685                 return gn, nil
686         }
687         return dn.treenode.Child(name, replace)
688 }
689
690 type fnSegmentRef struct {
691         fn  *filenode
692         idx int
693 }
694
695 // commitBlock concatenates the data from the given filenode segments
696 // (which must be *memSegments), writes the data out to Keep as a
697 // single block, and replaces the filenodes' *memSegments with
698 // storedSegments that reference the relevant portions of the new
699 // block.
700 //
701 // bufsize is the total data size in refs. It is used to preallocate
702 // the correct amount of memory when len(refs)>1.
703 //
704 // If sync is false, commitBlock returns right away, after starting a
705 // goroutine to do the writes, reacquire the filenodes' locks, and
706 // swap out the *memSegments. Some filenodes' segments might get
707 // modified/rearranged in the meantime, in which case commitBlock
708 // won't replace them.
709 //
710 // Caller must have write lock.
711 func (dn *dirnode) commitBlock(ctx context.Context, refs []fnSegmentRef, bufsize int, sync bool) error {
712         if len(refs) == 0 {
713                 return nil
714         }
715         if err := ctx.Err(); err != nil {
716                 return err
717         }
718         done := make(chan struct{})
719         var block []byte
720         segs := make([]*memSegment, 0, len(refs))
721         offsets := make([]int, 0, len(refs)) // location of segment's data within block
722         for _, ref := range refs {
723                 seg := ref.fn.segments[ref.idx].(*memSegment)
724                 if !sync && seg.flushingUnfinished() {
725                         // Let the other flushing goroutine finish. If
726                         // it fails, we'll try again next time.
727                         close(done)
728                         return nil
729                 }
730                 // In sync mode, we proceed regardless of
731                 // whether another flush is in progress: It
732                 // can't finish before we do, because we hold
733                 // fn's lock until we finish our own writes.
734                 seg.flushing = done
735                 offsets = append(offsets, len(block))
736                 if len(refs) == 1 {
737                         block = seg.buf
738                 } else if block == nil {
739                         block = append(make([]byte, 0, bufsize), seg.buf...)
740                 } else {
741                         block = append(block, seg.buf...)
742                 }
743                 segs = append(segs, seg)
744         }
745         blocksize := len(block)
746         dn.fs.throttle().Acquire()
747         errs := make(chan error, 1)
748         go func() {
749                 defer close(done)
750                 defer close(errs)
751                 locator, _, err := dn.fs.PutB(block)
752                 dn.fs.throttle().Release()
753                 if err != nil {
754                         errs <- err
755                         return
756                 }
757                 for idx, ref := range refs {
758                         if !sync {
759                                 ref.fn.Lock()
760                                 // In async mode, fn's lock was
761                                 // released while we were waiting for
762                                 // PutB(); lots of things might have
763                                 // changed.
764                                 if len(ref.fn.segments) <= ref.idx {
765                                         // file segments have
766                                         // rearranged or changed in
767                                         // some way
768                                         ref.fn.Unlock()
769                                         continue
770                                 } else if seg, ok := ref.fn.segments[ref.idx].(*memSegment); !ok || seg != segs[idx] {
771                                         // segment has been replaced
772                                         ref.fn.Unlock()
773                                         continue
774                                 } else if seg.flushing != done {
775                                         // seg.buf has been replaced
776                                         ref.fn.Unlock()
777                                         continue
778                                 }
779                         }
780                         data := ref.fn.segments[ref.idx].(*memSegment).buf
781                         ref.fn.segments[ref.idx] = storedSegment{
782                                 kc:      dn.fs,
783                                 locator: locator,
784                                 size:    blocksize,
785                                 offset:  offsets[idx],
786                                 length:  len(data),
787                         }
788                         // atomic is needed here despite caller having
789                         // lock: caller might be running concurrent
790                         // commitBlock() goroutines using the same
791                         // lock, writing different segments from the
792                         // same file.
793                         atomic.AddInt64(&ref.fn.memsize, -int64(len(data)))
794                         if !sync {
795                                 ref.fn.Unlock()
796                         }
797                 }
798         }()
799         if sync {
800                 return <-errs
801         }
802         return nil
803 }
804
805 type flushOpts struct {
806         sync        bool
807         shortBlocks bool
808 }
809
810 // flush in-memory data and remote-cluster block references (for the
811 // children with the given names, which must be children of dn) to
812 // local-cluster persistent storage.
813 //
814 // Caller must have write lock on dn and the named children.
815 //
816 // If any children are dirs, they will be flushed recursively.
817 func (dn *dirnode) flush(ctx context.Context, names []string, opts flushOpts) error {
818         cg := newContextGroup(ctx)
819         defer cg.Cancel()
820
821         goCommit := func(refs []fnSegmentRef, bufsize int) {
822                 cg.Go(func() error {
823                         return dn.commitBlock(cg.Context(), refs, bufsize, opts.sync)
824                 })
825         }
826
827         var pending []fnSegmentRef
828         var pendingLen int = 0
829         localLocator := map[string]string{}
830         for _, name := range names {
831                 switch node := dn.inodes[name].(type) {
832                 case *dirnode:
833                         grandchildNames := node.sortedNames()
834                         for _, grandchildName := range grandchildNames {
835                                 grandchild := node.inodes[grandchildName]
836                                 grandchild.Lock()
837                                 defer grandchild.Unlock()
838                         }
839                         cg.Go(func() error { return node.flush(cg.Context(), grandchildNames, opts) })
840                 case *filenode:
841                         for idx, seg := range node.segments {
842                                 switch seg := seg.(type) {
843                                 case storedSegment:
844                                         loc, ok := localLocator[seg.locator]
845                                         if !ok {
846                                                 var err error
847                                                 loc, err = dn.fs.LocalLocator(seg.locator)
848                                                 if err != nil {
849                                                         return err
850                                                 }
851                                                 localLocator[seg.locator] = loc
852                                         }
853                                         seg.locator = loc
854                                         node.segments[idx] = seg
855                                 case *memSegment:
856                                         if seg.Len() > maxBlockSize/2 {
857                                                 goCommit([]fnSegmentRef{{node, idx}}, seg.Len())
858                                                 continue
859                                         }
860                                         if pendingLen+seg.Len() > maxBlockSize {
861                                                 goCommit(pending, pendingLen)
862                                                 pending = nil
863                                                 pendingLen = 0
864                                         }
865                                         pending = append(pending, fnSegmentRef{node, idx})
866                                         pendingLen += seg.Len()
867                                 default:
868                                         panic(fmt.Sprintf("can't sync segment type %T", seg))
869                                 }
870                         }
871                 }
872         }
873         if opts.shortBlocks {
874                 goCommit(pending, pendingLen)
875         }
876         return cg.Wait()
877 }
878
879 // caller must have write lock.
880 func (dn *dirnode) MemorySize() (size int64) {
881         for _, name := range dn.sortedNames() {
882                 node := dn.inodes[name]
883                 node.Lock()
884                 defer node.Unlock()
885                 switch node := node.(type) {
886                 case *dirnode:
887                         size += node.MemorySize()
888                 case *filenode:
889                         for _, seg := range node.segments {
890                                 switch seg := seg.(type) {
891                                 case *memSegment:
892                                         size += int64(seg.Len())
893                                 }
894                         }
895                 }
896         }
897         return
898 }
899
900 // caller must have write lock.
901 func (dn *dirnode) sortedNames() []string {
902         names := make([]string, 0, len(dn.inodes))
903         for name := range dn.inodes {
904                 names = append(names, name)
905         }
906         sort.Strings(names)
907         return names
908 }
909
910 // caller must have write lock.
911 func (dn *dirnode) marshalManifest(ctx context.Context, prefix string) (string, error) {
912         cg := newContextGroup(ctx)
913         defer cg.Cancel()
914
915         if len(dn.inodes) == 0 {
916                 if prefix == "." {
917                         return "", nil
918                 }
919                 // Express the existence of an empty directory by
920                 // adding an empty file named `\056`, which (unlike
921                 // the more obvious spelling `.`) is accepted by the
922                 // API's manifest validator.
923                 return manifestEscape(prefix) + " d41d8cd98f00b204e9800998ecf8427e+0 0:0:\\056\n", nil
924         }
925
926         names := dn.sortedNames()
927
928         // Wait for children to finish any pending write operations
929         // before locking them.
930         for _, name := range names {
931                 node := dn.inodes[name]
932                 if fn, ok := node.(*filenode); ok {
933                         fn.waitPrune()
934                 }
935         }
936
937         var dirnames []string
938         var filenames []string
939         for _, name := range names {
940                 node := dn.inodes[name]
941                 node.Lock()
942                 defer node.Unlock()
943                 switch node := node.(type) {
944                 case *dirnode:
945                         dirnames = append(dirnames, name)
946                 case *filenode:
947                         filenames = append(filenames, name)
948                 default:
949                         panic(fmt.Sprintf("can't marshal inode type %T", node))
950                 }
951         }
952
953         subdirs := make([]string, len(dirnames))
954         rootdir := ""
955         for i, name := range dirnames {
956                 i, name := i, name
957                 cg.Go(func() error {
958                         txt, err := dn.inodes[name].(*dirnode).marshalManifest(cg.Context(), prefix+"/"+name)
959                         subdirs[i] = txt
960                         return err
961                 })
962         }
963
964         cg.Go(func() error {
965                 var streamLen int64
966                 type filepart struct {
967                         name   string
968                         offset int64
969                         length int64
970                 }
971
972                 var fileparts []filepart
973                 var blocks []string
974                 if err := dn.flush(cg.Context(), filenames, flushOpts{sync: true, shortBlocks: true}); err != nil {
975                         return err
976                 }
977                 for _, name := range filenames {
978                         node := dn.inodes[name].(*filenode)
979                         if len(node.segments) == 0 {
980                                 fileparts = append(fileparts, filepart{name: name})
981                                 continue
982                         }
983                         for _, seg := range node.segments {
984                                 switch seg := seg.(type) {
985                                 case storedSegment:
986                                         if len(blocks) > 0 && blocks[len(blocks)-1] == seg.locator {
987                                                 streamLen -= int64(seg.size)
988                                         } else {
989                                                 blocks = append(blocks, seg.locator)
990                                         }
991                                         next := filepart{
992                                                 name:   name,
993                                                 offset: streamLen + int64(seg.offset),
994                                                 length: int64(seg.length),
995                                         }
996                                         if prev := len(fileparts) - 1; prev >= 0 &&
997                                                 fileparts[prev].name == name &&
998                                                 fileparts[prev].offset+fileparts[prev].length == next.offset {
999                                                 fileparts[prev].length += next.length
1000                                         } else {
1001                                                 fileparts = append(fileparts, next)
1002                                         }
1003                                         streamLen += int64(seg.size)
1004                                 default:
1005                                         // This can't happen: we
1006                                         // haven't unlocked since
1007                                         // calling flush(sync=true).
1008                                         panic(fmt.Sprintf("can't marshal segment type %T", seg))
1009                                 }
1010                         }
1011                 }
1012                 var filetokens []string
1013                 for _, s := range fileparts {
1014                         filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
1015                 }
1016                 if len(filetokens) == 0 {
1017                         return nil
1018                 } else if len(blocks) == 0 {
1019                         blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
1020                 }
1021                 rootdir = manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n"
1022                 return nil
1023         })
1024         err := cg.Wait()
1025         return rootdir + strings.Join(subdirs, ""), err
1026 }
1027
1028 func (dn *dirnode) loadManifest(txt string) error {
1029         var dirname string
1030         streams := strings.Split(txt, "\n")
1031         if streams[len(streams)-1] != "" {
1032                 return fmt.Errorf("line %d: no trailing newline", len(streams))
1033         }
1034         streams = streams[:len(streams)-1]
1035         segments := []storedSegment{}
1036         for i, stream := range streams {
1037                 lineno := i + 1
1038                 var anyFileTokens bool
1039                 var pos int64
1040                 var segIdx int
1041                 segments = segments[:0]
1042                 for i, token := range strings.Split(stream, " ") {
1043                         if i == 0 {
1044                                 dirname = manifestUnescape(token)
1045                                 continue
1046                         }
1047                         if !strings.Contains(token, ":") {
1048                                 if anyFileTokens {
1049                                         return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1050                                 }
1051                                 toks := strings.SplitN(token, "+", 3)
1052                                 if len(toks) < 2 {
1053                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1054                                 }
1055                                 length, err := strconv.ParseInt(toks[1], 10, 32)
1056                                 if err != nil || length < 0 {
1057                                         return fmt.Errorf("line %d: bad locator %q", lineno, token)
1058                                 }
1059                                 segments = append(segments, storedSegment{
1060                                         locator: token,
1061                                         size:    int(length),
1062                                         offset:  0,
1063                                         length:  int(length),
1064                                 })
1065                                 continue
1066                         } else if len(segments) == 0 {
1067                                 return fmt.Errorf("line %d: bad locator %q", lineno, token)
1068                         }
1069
1070                         toks := strings.SplitN(token, ":", 3)
1071                         if len(toks) != 3 {
1072                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1073                         }
1074                         anyFileTokens = true
1075
1076                         offset, err := strconv.ParseInt(toks[0], 10, 64)
1077                         if err != nil || offset < 0 {
1078                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1079                         }
1080                         length, err := strconv.ParseInt(toks[1], 10, 64)
1081                         if err != nil || length < 0 {
1082                                 return fmt.Errorf("line %d: bad file segment %q", lineno, token)
1083                         }
1084                         name := dirname + "/" + manifestUnescape(toks[2])
1085                         fnode, err := dn.createFileAndParents(name)
1086                         if fnode == nil && err == nil && length == 0 {
1087                                 // Special case: an empty file used as
1088                                 // a marker to preserve an otherwise
1089                                 // empty directory in a manifest.
1090                                 continue
1091                         }
1092                         if err != nil || (fnode == nil && length != 0) {
1093                                 return fmt.Errorf("line %d: cannot use path %q with length %d: %s", lineno, name, length, err)
1094                         }
1095                         // Map the stream offset/range coordinates to
1096                         // block/offset/range coordinates and add
1097                         // corresponding storedSegments to the filenode
1098                         if pos > offset {
1099                                 // Can't continue where we left off.
1100                                 // TODO: binary search instead of
1101                                 // rewinding all the way (but this
1102                                 // situation might be rare anyway)
1103                                 segIdx, pos = 0, 0
1104                         }
1105                         for ; segIdx < len(segments); segIdx++ {
1106                                 seg := segments[segIdx]
1107                                 next := pos + int64(seg.Len())
1108                                 if next <= offset || seg.Len() == 0 {
1109                                         pos = next
1110                                         continue
1111                                 }
1112                                 if pos >= offset+length {
1113                                         break
1114                                 }
1115                                 var blkOff int
1116                                 if pos < offset {
1117                                         blkOff = int(offset - pos)
1118                                 }
1119                                 blkLen := seg.Len() - blkOff
1120                                 if pos+int64(blkOff+blkLen) > offset+length {
1121                                         blkLen = int(offset + length - pos - int64(blkOff))
1122                                 }
1123                                 fnode.appendSegment(storedSegment{
1124                                         kc:      dn.fs,
1125                                         locator: seg.locator,
1126                                         size:    seg.size,
1127                                         offset:  blkOff,
1128                                         length:  blkLen,
1129                                 })
1130                                 if next > offset+length {
1131                                         break
1132                                 } else {
1133                                         pos = next
1134                                 }
1135                         }
1136                         if segIdx == len(segments) && pos < offset+length {
1137                                 return fmt.Errorf("line %d: invalid segment in %d-byte stream: %q", lineno, pos, token)
1138                         }
1139                 }
1140                 if !anyFileTokens {
1141                         return fmt.Errorf("line %d: no file segments", lineno)
1142                 } else if len(segments) == 0 {
1143                         return fmt.Errorf("line %d: no locators", lineno)
1144                 } else if dirname == "" {
1145                         return fmt.Errorf("line %d: no stream name", lineno)
1146                 }
1147         }
1148         return nil
1149 }
1150
1151 // only safe to call from loadManifest -- no locking.
1152 //
1153 // If path is a "parent directory exists" marker (the last path
1154 // component is "."), the returned values are both nil.
1155 func (dn *dirnode) createFileAndParents(path string) (fn *filenode, err error) {
1156         var node inode = dn
1157         names := strings.Split(path, "/")
1158         basename := names[len(names)-1]
1159         for _, name := range names[:len(names)-1] {
1160                 switch name {
1161                 case "", ".":
1162                         continue
1163                 case "..":
1164                         if node == dn {
1165                                 // can't be sure parent will be a *dirnode
1166                                 return nil, ErrInvalidArgument
1167                         }
1168                         node = node.Parent()
1169                         continue
1170                 }
1171                 modtime := node.Parent().FileInfo().ModTime()
1172                 node.Lock()
1173                 locked := node
1174                 node, err = node.Child(name, func(child inode) (inode, error) {
1175                         if child == nil {
1176                                 child, err := node.FS().newNode(name, 0755|os.ModeDir, modtime)
1177                                 if err != nil {
1178                                         return nil, err
1179                                 }
1180                                 child.SetParent(node, name)
1181                                 return child, nil
1182                         } else if !child.IsDir() {
1183                                 return child, ErrFileExists
1184                         } else {
1185                                 return child, nil
1186                         }
1187                 })
1188                 locked.Unlock()
1189                 if err != nil {
1190                         return
1191                 }
1192         }
1193         if basename == "." {
1194                 return
1195         } else if !permittedName(basename) {
1196                 err = fmt.Errorf("invalid file part %q in path %q", basename, path)
1197                 return
1198         }
1199         modtime := node.FileInfo().ModTime()
1200         node.Lock()
1201         defer node.Unlock()
1202         _, err = node.Child(basename, func(child inode) (inode, error) {
1203                 switch child := child.(type) {
1204                 case nil:
1205                         child, err = node.FS().newNode(basename, 0755, modtime)
1206                         if err != nil {
1207                                 return nil, err
1208                         }
1209                         child.SetParent(node, basename)
1210                         fn = child.(*filenode)
1211                         return child, nil
1212                 case *filenode:
1213                         fn = child
1214                         return child, nil
1215                 case *dirnode:
1216                         return child, ErrIsDirectory
1217                 default:
1218                         return child, ErrInvalidArgument
1219                 }
1220         })
1221         return
1222 }
1223
1224 func (dn *dirnode) TreeSize() (bytes int64) {
1225         dn.RLock()
1226         defer dn.RUnlock()
1227         for _, i := range dn.inodes {
1228                 switch i := i.(type) {
1229                 case *filenode:
1230                         bytes += i.Size()
1231                 case *dirnode:
1232                         bytes += i.TreeSize()
1233                 }
1234         }
1235         return
1236 }
1237
1238 type segment interface {
1239         io.ReaderAt
1240         Len() int
1241         // Return a new segment with a subsection of the data from this
1242         // one. length<0 means length=Len()-off.
1243         Slice(off int, length int) segment
1244 }
1245
1246 type memSegment struct {
1247         buf []byte
1248         // If flushing is not nil and not ready/closed, then a) buf is
1249         // being shared by a pruneMemSegments goroutine, and must be
1250         // copied on write; and b) the flushing channel will close
1251         // when the goroutine finishes, whether it succeeds or not.
1252         flushing <-chan struct{}
1253 }
1254
1255 func (me *memSegment) flushingUnfinished() bool {
1256         if me.flushing == nil {
1257                 return false
1258         }
1259         select {
1260         case <-me.flushing:
1261                 me.flushing = nil
1262                 return false
1263         default:
1264                 return true
1265         }
1266 }
1267
1268 func (me *memSegment) Len() int {
1269         return len(me.buf)
1270 }
1271
1272 func (me *memSegment) Slice(off, length int) segment {
1273         if length < 0 {
1274                 length = len(me.buf) - off
1275         }
1276         buf := make([]byte, length)
1277         copy(buf, me.buf[off:])
1278         return &memSegment{buf: buf}
1279 }
1280
1281 func (me *memSegment) Truncate(n int) {
1282         if n > cap(me.buf) || (me.flushing != nil && n > len(me.buf)) {
1283                 newsize := 1024
1284                 for newsize < n {
1285                         newsize = newsize << 2
1286                 }
1287                 newbuf := make([]byte, n, newsize)
1288                 copy(newbuf, me.buf)
1289                 me.buf, me.flushing = newbuf, nil
1290         } else {
1291                 // reclaim existing capacity, and zero reclaimed part
1292                 oldlen := len(me.buf)
1293                 me.buf = me.buf[:n]
1294                 for i := oldlen; i < n; i++ {
1295                         me.buf[i] = 0
1296                 }
1297         }
1298 }
1299
1300 func (me *memSegment) WriteAt(p []byte, off int) {
1301         if off+len(p) > len(me.buf) {
1302                 panic("overflowed segment")
1303         }
1304         if me.flushing != nil {
1305                 me.buf, me.flushing = append([]byte(nil), me.buf...), nil
1306         }
1307         copy(me.buf[off:], p)
1308 }
1309
1310 func (me *memSegment) ReadAt(p []byte, off int64) (n int, err error) {
1311         if off > int64(me.Len()) {
1312                 err = io.EOF
1313                 return
1314         }
1315         n = copy(p, me.buf[int(off):])
1316         if n < len(p) {
1317                 err = io.EOF
1318         }
1319         return
1320 }
1321
1322 type storedSegment struct {
1323         kc      fsBackend
1324         locator string
1325         size    int // size of stored block (also encoded in locator)
1326         offset  int // position of segment within the stored block
1327         length  int // bytes in this segment (offset + length <= size)
1328 }
1329
1330 func (se storedSegment) Len() int {
1331         return se.length
1332 }
1333
1334 func (se storedSegment) Slice(n, size int) segment {
1335         se.offset += n
1336         se.length -= n
1337         if size >= 0 && se.length > size {
1338                 se.length = size
1339         }
1340         return se
1341 }
1342
1343 func (se storedSegment) ReadAt(p []byte, off int64) (n int, err error) {
1344         if off > int64(se.length) {
1345                 return 0, io.EOF
1346         }
1347         maxlen := se.length - int(off)
1348         if len(p) > maxlen {
1349                 p = p[:maxlen]
1350                 n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1351                 if err == nil {
1352                         err = io.EOF
1353                 }
1354                 return
1355         }
1356         return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
1357 }
1358
1359 func canonicalName(name string) string {
1360         name = path.Clean("/" + name)
1361         if name == "/" || name == "./" {
1362                 name = "."
1363         } else if strings.HasPrefix(name, "/") {
1364                 name = "." + name
1365         }
1366         return name
1367 }
1368
1369 var manifestEscapeSeq = regexp.MustCompile(`\\([0-7]{3}|\\)`)
1370
1371 func manifestUnescapeFunc(seq string) string {
1372         if seq == `\\` {
1373                 return `\`
1374         }
1375         i, err := strconv.ParseUint(seq[1:], 8, 8)
1376         if err != nil {
1377                 // Invalid escape sequence: can't unescape.
1378                 return seq
1379         }
1380         return string([]byte{byte(i)})
1381 }
1382
1383 func manifestUnescape(s string) string {
1384         return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
1385 }
1386
1387 var manifestEscapedChar = regexp.MustCompile(`[\000-\040:\s\\]`)
1388
1389 func manifestEscapeFunc(seq string) string {
1390         return fmt.Sprintf("\\%03o", byte(seq[0]))
1391 }
1392
1393 func manifestEscape(s string) string {
1394         return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)
1395 }