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