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