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