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