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