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