-
Notifications
You must be signed in to change notification settings - Fork 468
/
mem_fs.go
710 lines (654 loc) · 16.1 KB
/
mem_fs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package vfs // import "github.com/cockroachdb/pebble/vfs"
import (
"bytes"
"fmt"
"io"
"os"
"path"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/pebble/internal/invariants"
)
const sep = "/"
// NewMem returns a new memory-backed FS implementation.
func NewMem() *MemFS {
return &MemFS{
root: newRootMemNode(),
}
}
// NewStrictMem returns a "strict" memory-backed FS implementation. The behaviour is strict wrt
// needing a Sync() call on files or directories for the state changes to be finalized. Any
// changes that are not finalized are visible to reads until MemFS.ResetToSyncedState() is called,
// at which point they are discarded and no longer visible.
//
// Expected usage:
// strictFS := NewStrictMem()
// db := Open(..., &Options{FS: strictFS})
// // Do and commit various operations.
// ...
// // Prevent any more changes to finalized state.
// strictFS.SetIgnoreSyncs(true)
// // This will finish any ongoing background flushes, compactions but none of these writes will
// // be finalized since syncs are being ignored.
// db.Close()
// // Discard unsynced state.
// strictFS.ResetToSyncedState()
// // Allow changes to finalized state.
// strictFS.SetIgnoreSyncs(false)
// // Open the DB. This DB should have the same state as if the earlier strictFS operations and
// // db.Close() were not called.
// db := Open(..., &Options{FS: strictFS})
func NewStrictMem() *MemFS {
return &MemFS{
root: newRootMemNode(),
strict: true,
}
}
// NewMemFile returns a memory-backed File implementation. The memory-backed
// file takes ownership of data.
func NewMemFile(data []byte) File {
n := &memNode{refs: 1}
n.mu.data = data
n.mu.modTime = time.Now()
return &memFile{
n: n,
read: true,
}
}
// MemFS implements FS.
type MemFS struct {
mu sync.Mutex
root *memNode
strict bool
ignoreSyncs bool
}
var _ FS = &MemFS{}
// String dumps the contents of the MemFS.
func (y *MemFS) String() string {
y.mu.Lock()
defer y.mu.Unlock()
s := new(bytes.Buffer)
y.root.dump(s, 0)
return s.String()
}
// SetIgnoreSyncs sets the MemFS.ignoreSyncs field. See the usage comment with NewStrictMem() for
// details.
func (y *MemFS) SetIgnoreSyncs(ignoreSyncs bool) {
y.mu.Lock()
if !y.strict {
// noop
return
}
y.ignoreSyncs = ignoreSyncs
y.mu.Unlock()
}
// ResetToSyncedState discards state in the FS that is not synced. See the usage comment with
// NewStrictMem() for details.
func (y *MemFS) ResetToSyncedState() {
if !y.strict {
// noop
return
}
y.mu.Lock()
y.root.resetToSyncedState()
y.mu.Unlock()
}
// walk walks the directory tree for the fullname, calling f at each step. If
// f returns an error, the walk will be aborted and return that same error.
//
// Each walk is atomic: y's mutex is held for the entire operation, including
// all calls to f.
//
// dir is the directory at that step, frag is the name fragment, and final is
// whether it is the final step. For example, walking "/foo/bar/x" will result
// in 3 calls to f:
// - "/", "foo", false
// - "/foo/", "bar", false
// - "/foo/bar/", "x", true
// Similarly, walking "/y/z/", with a trailing slash, will result in 3 calls to f:
// - "/", "y", false
// - "/y/", "z", false
// - "/y/z/", "", true
func (y *MemFS) walk(fullname string, f func(dir *memNode, frag string, final bool) error) error {
y.mu.Lock()
defer y.mu.Unlock()
// For memfs, the current working directory is the same as the root directory,
// so we strip off any leading "/"s to make fullname a relative path, and
// the walk starts at y.root.
for len(fullname) > 0 && fullname[0] == sep[0] {
fullname = fullname[1:]
}
dir := y.root
for {
frag, remaining := fullname, ""
i := strings.IndexRune(fullname, rune(sep[0]))
final := i < 0
if !final {
frag, remaining = fullname[:i], fullname[i+1:]
for len(remaining) > 0 && remaining[0] == sep[0] {
remaining = remaining[1:]
}
}
if err := f(dir, frag, final); err != nil {
return err
}
if final {
break
}
child := dir.children[frag]
if child == nil {
return &os.PathError{
Op: "open",
Path: fullname,
Err: oserror.ErrNotExist,
}
}
if !child.isDir {
return &os.PathError{
Op: "open",
Path: fullname,
Err: errors.New("not a directory"),
}
}
dir, fullname = child, remaining
}
return nil
}
// Create implements FS.Create.
func (y *MemFS) Create(fullname string) (File, error) {
var ret *memFile
err := y.walk(fullname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
n := &memNode{name: frag}
dir.children[frag] = n
ret = &memFile{
n: n,
fs: y,
write: true,
}
}
return nil
})
if err != nil {
return nil, err
}
atomic.AddInt32(&ret.n.refs, 1)
return ret, nil
}
// Link implements FS.Link.
func (y *MemFS) Link(oldname, newname string) error {
var n *memNode
err := y.walk(oldname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
n = dir.children[frag]
}
return nil
})
if err != nil {
return err
}
if n == nil {
return &os.LinkError{
Op: "link",
Old: oldname,
New: newname,
Err: oserror.ErrNotExist,
}
}
return y.walk(newname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
if _, ok := dir.children[frag]; ok {
return &os.LinkError{
Op: "link",
Old: oldname,
New: newname,
Err: oserror.ErrExist,
}
}
dir.children[frag] = n
}
return nil
})
}
func (y *MemFS) open(fullname string) (File, error) {
var ret *memFile
err := y.walk(fullname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
ret = &memFile{
n: dir,
fs: y,
}
return nil
}
if n := dir.children[frag]; n != nil {
ret = &memFile{
n: n,
fs: y,
read: true,
}
}
}
return nil
})
if err != nil {
return nil, err
}
if ret == nil {
return nil, &os.PathError{
Op: "open",
Path: fullname,
Err: oserror.ErrNotExist,
}
}
atomic.AddInt32(&ret.n.refs, 1)
return ret, nil
}
// Open implements FS.Open.
func (y *MemFS) Open(fullname string, opts ...OpenOption) (File, error) {
return y.open(fullname)
}
// OpenDir implements FS.OpenDir.
func (y *MemFS) OpenDir(fullname string) (File, error) {
return y.open(fullname)
}
// Remove implements FS.Remove.
func (y *MemFS) Remove(fullname string) error {
return y.walk(fullname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
child, ok := dir.children[frag]
if !ok {
return oserror.ErrNotExist
}
// Disallow removal of open files/directories which implements Windows
// semantics. This ensures that we don't regress in the ordering of
// operations and try to remove a file while it is still open.
if n := atomic.LoadInt32(&child.refs); n > 0 {
return oserror.ErrInvalid
}
if len(child.children) > 0 {
return errNotEmpty
}
delete(dir.children, frag)
}
return nil
})
}
// RemoveAll implements FS.RemoveAll.
func (y *MemFS) RemoveAll(fullname string) error {
err := y.walk(fullname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
_, ok := dir.children[frag]
if !ok {
return nil
}
delete(dir.children, frag)
}
return nil
})
// Match os.RemoveAll which returns a nil error even if the parent
// directories don't exist.
if oserror.IsNotExist(err) {
err = nil
}
return err
}
// Rename implements FS.Rename.
func (y *MemFS) Rename(oldname, newname string) error {
var n *memNode
err := y.walk(oldname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
n = dir.children[frag]
delete(dir.children, frag)
}
return nil
})
if err != nil {
return err
}
if n == nil {
return &os.PathError{
Op: "open",
Path: oldname,
Err: oserror.ErrNotExist,
}
}
return y.walk(newname, func(dir *memNode, frag string, final bool) error {
if final {
if frag == "" {
return errors.New("pebble/vfs: empty file name")
}
dir.children[frag] = n
n.name = frag
}
return nil
})
}
// ReuseForWrite implements FS.ReuseForWrite.
func (y *MemFS) ReuseForWrite(oldname, newname string) (File, error) {
if err := y.Rename(oldname, newname); err != nil {
return nil, err
}
f, err := y.Open(newname)
if err != nil {
return nil, err
}
y.mu.Lock()
defer y.mu.Unlock()
mf := f.(*memFile)
mf.read = false
mf.write = true
return f, nil
}
// MkdirAll implements FS.MkdirAll.
func (y *MemFS) MkdirAll(dirname string, perm os.FileMode) error {
return y.walk(dirname, func(dir *memNode, frag string, final bool) error {
if frag == "" {
if final {
return nil
}
return errors.New("pebble/vfs: empty file name")
}
child := dir.children[frag]
if child == nil {
dir.children[frag] = &memNode{
name: frag,
children: make(map[string]*memNode),
isDir: true,
}
return nil
}
if !child.isDir {
return &os.PathError{
Op: "open",
Path: dirname,
Err: errors.New("not a directory"),
}
}
return nil
})
}
// Lock implements FS.Lock.
func (y *MemFS) Lock(fullname string) (io.Closer, error) {
// FS.Lock excludes other processes, but other processes cannot see this
// process' memory. We translate Lock into Create so that have the normal
// detection of non-existent directory paths.
return y.Create(fullname)
}
// List implements FS.List.
func (y *MemFS) List(dirname string) ([]string, error) {
if !strings.HasSuffix(dirname, sep) {
dirname += sep
}
var ret []string
err := y.walk(dirname, func(dir *memNode, frag string, final bool) error {
if final {
if frag != "" {
panic("unreachable")
}
ret = make([]string, 0, len(dir.children))
for s := range dir.children {
ret = append(ret, s)
}
}
return nil
})
return ret, err
}
// Stat implements FS.Stat.
func (y *MemFS) Stat(name string) (os.FileInfo, error) {
f, err := y.Open(name)
if err != nil {
if pe, ok := err.(*os.PathError); ok {
pe.Op = "stat"
}
return nil, err
}
defer f.Close()
return f.Stat()
}
// PathBase implements FS.PathBase.
func (*MemFS) PathBase(p string) string {
// Note that MemFS uses forward slashes for its separator, hence the use of
// path.Base, not filepath.Base.
return path.Base(p)
}
// PathJoin implements FS.PathJoin.
func (*MemFS) PathJoin(elem ...string) string {
// Note that MemFS uses forward slashes for its separator, hence the use of
// path.Join, not filepath.Join.
return path.Join(elem...)
}
// PathDir implements FS.PathDir.
func (*MemFS) PathDir(p string) string {
// Note that MemFS uses forward slashes for its separator, hence the use of
// path.Dir, not filepath.Dir.
return path.Dir(p)
}
// GetDiskUsage implements FS.GetDiskUsage.
func (*MemFS) GetDiskUsage(string) (DiskUsage, error) {
return DiskUsage{}, ErrUnsupported
}
// memNode holds a file's data or a directory's children, and implements os.FileInfo.
type memNode struct {
name string
isDir bool
refs int32
// Mutable state.
// - For a file: data, syncedDate, modTime: A file is only being mutated by a single goroutine,
// but there can be concurrent readers e.g. DB.Checkpoint() which can read WAL or MANIFEST
// files that are being written to. Additionally Sync() calls can be concurrent with writing.
// - For a directory: children and syncedChildren. Concurrent writes are possible, and
// these are protected using MemFS.mu.
mu struct {
sync.Mutex
data []byte
syncedData []byte
modTime time.Time
}
children map[string]*memNode
syncedChildren map[string]*memNode
}
func newRootMemNode() *memNode {
return &memNode{
name: "/", // set the name to match what file systems do
children: make(map[string]*memNode),
isDir: true,
}
}
func (f *memNode) IsDir() bool {
return f.isDir
}
func (f *memNode) ModTime() time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return f.mu.modTime
}
func (f *memNode) Mode() os.FileMode {
if f.isDir {
return os.ModeDir | 0755
}
return 0755
}
func (f *memNode) Name() string {
return f.name
}
func (f *memNode) Size() int64 {
f.mu.Lock()
defer f.mu.Unlock()
return int64(len(f.mu.data))
}
func (f *memNode) Sys() interface{} {
return nil
}
func (f *memNode) dump(w *bytes.Buffer, level int) {
if f.isDir {
w.WriteString(" ")
} else {
f.mu.Lock()
fmt.Fprintf(w, "%8d ", len(f.mu.data))
f.mu.Unlock()
}
for i := 0; i < level; i++ {
w.WriteString(" ")
}
w.WriteString(f.name)
if !f.isDir {
w.WriteByte('\n')
return
}
if level > 0 { // deal with the fact that the root's name is already "/"
w.WriteByte(sep[0])
}
w.WriteByte('\n')
names := make([]string, 0, len(f.children))
for name := range f.children {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
f.children[name].dump(w, level+1)
}
}
func (f *memNode) resetToSyncedState() {
if f.isDir {
f.children = make(map[string]*memNode)
for k, v := range f.syncedChildren {
f.children[k] = v
}
for _, v := range f.children {
v.resetToSyncedState()
}
} else {
f.mu.Lock()
f.mu.data = append([]byte(nil), f.mu.syncedData...)
f.mu.Unlock()
}
}
// memFile is a reader or writer of a node's data, and implements File.
type memFile struct {
n *memNode
fs *MemFS // nil for a standalone memFile
rpos int
wpos int
read, write bool
}
func (f *memFile) Close() error {
if n := atomic.AddInt32(&f.n.refs, -1); n < 0 {
panic(fmt.Sprintf("pebble: close of unopened file: %d", n))
}
f.n = nil
return nil
}
func (f *memFile) Read(p []byte) (int, error) {
if !f.read {
return 0, errors.New("pebble/vfs: file was not opened for reading")
}
if f.n.isDir {
return 0, errors.New("pebble/vfs: cannot read a directory")
}
f.n.mu.Lock()
defer f.n.mu.Unlock()
if f.rpos >= len(f.n.mu.data) {
return 0, io.EOF
}
n := copy(p, f.n.mu.data[f.rpos:])
f.rpos += n
return n, nil
}
func (f *memFile) ReadAt(p []byte, off int64) (int, error) {
if !f.read {
return 0, errors.New("pebble/vfs: file was not opened for reading")
}
if f.n.isDir {
return 0, errors.New("pebble/vfs: cannot read a directory")
}
f.n.mu.Lock()
defer f.n.mu.Unlock()
if off >= int64(len(f.n.mu.data)) {
return 0, io.EOF
}
return copy(p, f.n.mu.data[off:]), nil
}
func (f *memFile) Write(p []byte) (int, error) {
if !f.write {
return 0, errors.New("pebble/vfs: file was not created for writing")
}
if f.n.isDir {
return 0, errors.New("pebble/vfs: cannot write a directory")
}
f.n.mu.Lock()
defer f.n.mu.Unlock()
f.n.mu.modTime = time.Now()
if f.wpos+len(p) <= len(f.n.mu.data) {
n := copy(f.n.mu.data[f.wpos:f.wpos+len(p)], p)
if n != len(p) {
panic("stuff")
}
} else {
f.n.mu.data = append(f.n.mu.data[:f.wpos], p...)
}
f.wpos += len(p)
if invariants.Enabled {
// Mutate the input buffer to flush out bugs in Pebble which expect the
// input buffer to be unmodified.
for i := range p {
p[i] ^= 0xff
}
}
return len(p), nil
}
func (f *memFile) Stat() (os.FileInfo, error) {
return f.n, nil
}
func (f *memFile) Sync() error {
if f.fs != nil && f.fs.strict {
f.fs.mu.Lock()
defer f.fs.mu.Unlock()
if f.fs.ignoreSyncs {
return nil
}
if f.n.isDir {
f.n.syncedChildren = make(map[string]*memNode)
for k, v := range f.n.children {
f.n.syncedChildren[k] = v
}
} else {
f.n.mu.Lock()
f.n.mu.syncedData = append([]byte(nil), f.n.mu.data...)
f.n.mu.Unlock()
}
}
return nil
}
// Flush is a no-op and present only to prevent buffering at higher levels
// (e.g. it prevents sstable.Writer from using a bufio.Writer).
func (f *memFile) Flush() error {
return nil
}