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