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 : "slices"
14 : "sort"
15 : "strings"
16 : "sync"
17 : "sync/atomic"
18 : "syscall"
19 : "time"
20 :
21 : "github.com/cockroachdb/errors"
22 : "github.com/cockroachdb/errors/oserror"
23 : "github.com/cockroachdb/pebble/internal/invariants"
24 : )
25 :
26 : const sep = "/"
27 :
28 : // NewMem returns a new memory-backed FS implementation.
29 1 : func NewMem() *MemFS {
30 1 : return &MemFS{
31 1 : root: newRootMemNode(),
32 1 : }
33 1 : }
34 :
35 : // NewStrictMem returns a "strict" memory-backed FS implementation. The behaviour is strict wrt
36 : // needing a Sync() call on files or directories for the state changes to be finalized. Any
37 : // changes that are not finalized are visible to reads until MemFS.ResetToSyncedState() is called,
38 : // at which point they are discarded and no longer visible.
39 : //
40 : // Expected usage:
41 : //
42 : // strictFS := NewStrictMem()
43 : // db := Open(..., &Options{FS: strictFS})
44 : // // Do and commit various operations.
45 : // ...
46 : // // Prevent any more changes to finalized state.
47 : // strictFS.SetIgnoreSyncs(true)
48 : // // This will finish any ongoing background flushes, compactions but none of these writes will
49 : // // be finalized since syncs are being ignored.
50 : // db.Close()
51 : // // Discard unsynced state.
52 : // strictFS.ResetToSyncedState()
53 : // // Allow changes to finalized state.
54 : // strictFS.SetIgnoreSyncs(false)
55 : // // Open the DB. This DB should have the same state as if the earlier strictFS operations and
56 : // // db.Close() were not called.
57 : // db := Open(..., &Options{FS: strictFS})
58 1 : func NewStrictMem() *MemFS {
59 1 : return &MemFS{
60 1 : root: newRootMemNode(),
61 1 : strict: true,
62 1 : }
63 1 : }
64 :
65 : // NewMemFile returns a memory-backed File implementation. The memory-backed
66 : // file takes ownership of data.
67 0 : func NewMemFile(data []byte) File {
68 0 : n := &memNode{}
69 0 : n.refs.Store(1)
70 0 : n.mu.data = data
71 0 : n.mu.modTime = time.Now()
72 0 : return &memFile{
73 0 : n: n,
74 0 : read: true,
75 0 : }
76 0 : }
77 :
78 : // MemFS implements FS.
79 : type MemFS struct {
80 : mu sync.Mutex
81 : root *memNode
82 :
83 : // lockFiles holds a map of open file locks. Presence in this map indicates
84 : // a file lock is currently held. Keys are strings holding the path of the
85 : // locked file. The stored value is untyped and unused; only presence of
86 : // the key within the map is significant.
87 : lockedFiles sync.Map
88 : strict bool
89 : ignoreSyncs bool
90 : // Windows has peculiar semantics with respect to hard links and deleting
91 : // open files. In tests meant to exercise this behavior, this flag can be
92 : // set to error if removing an open file.
93 : windowsSemantics bool
94 : }
95 :
96 : var _ FS = &MemFS{}
97 :
98 : // UseWindowsSemantics configures whether the MemFS implements Windows-style
99 : // semantics, in particular with respect to whether any of an open file's links
100 : // may be removed. Windows semantics default to off.
101 0 : func (y *MemFS) UseWindowsSemantics(windowsSemantics bool) {
102 0 : y.mu.Lock()
103 0 : defer y.mu.Unlock()
104 0 : y.windowsSemantics = windowsSemantics
105 0 : }
106 :
107 : // String dumps the contents of the MemFS.
108 0 : func (y *MemFS) String() string {
109 0 : y.mu.Lock()
110 0 : defer y.mu.Unlock()
111 0 :
112 0 : s := new(bytes.Buffer)
113 0 : y.root.dump(s, 0, sep)
114 0 : return s.String()
115 0 : }
116 :
117 : // SetIgnoreSyncs sets the MemFS.ignoreSyncs field. See the usage comment with NewStrictMem() for
118 : // details.
119 0 : func (y *MemFS) SetIgnoreSyncs(ignoreSyncs bool) {
120 0 : if !y.strict {
121 0 : panic("SetIgnoreSyncs can only be used on a strict MemFS")
122 : }
123 0 : y.mu.Lock()
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 : panic("ResetToSyncedState can only be used on a strict MemFS")
133 : }
134 0 : y.mu.Lock()
135 0 : y.root.resetToSyncedState()
136 0 : y.mu.Unlock()
137 : }
138 :
139 : // walk walks the directory tree for the fullname, calling f at each step. If
140 : // f returns an error, the walk will be aborted and return that same error.
141 : //
142 : // Each walk is atomic: y's mutex is held for the entire operation, including
143 : // all calls to f.
144 : //
145 : // dir is the directory at that step, frag is the name fragment, and final is
146 : // whether it is the final step. For example, walking "/foo/bar/x" will result
147 : // in 3 calls to f:
148 : // - "/", "foo", false
149 : // - "/foo/", "bar", false
150 : // - "/foo/bar/", "x", true
151 : //
152 : // Similarly, walking "/y/z/", with a trailing slash, will result in 3 calls to f:
153 : // - "/", "y", false
154 : // - "/y/", "z", false
155 : // - "/y/z/", "", true
156 1 : func (y *MemFS) walk(fullname string, f func(dir *memNode, frag string, final bool) error) error {
157 1 : y.mu.Lock()
158 1 : defer y.mu.Unlock()
159 1 :
160 1 : // For memfs, the current working directory is the same as the root directory,
161 1 : // so we strip off any leading "/"s to make fullname a relative path, and
162 1 : // the walk starts at y.root.
163 1 : for len(fullname) > 0 && fullname[0] == sep[0] {
164 1 : fullname = fullname[1:]
165 1 : }
166 1 : dir := y.root
167 1 :
168 1 : for {
169 1 : frag, remaining := fullname, ""
170 1 : i := strings.IndexRune(fullname, rune(sep[0]))
171 1 : final := i < 0
172 1 : if !final {
173 1 : frag, remaining = fullname[:i], fullname[i+1:]
174 1 : for len(remaining) > 0 && remaining[0] == sep[0] {
175 0 : remaining = remaining[1:]
176 0 : }
177 : }
178 1 : if err := f(dir, frag, final); err != nil {
179 0 : return err
180 0 : }
181 1 : if final {
182 1 : break
183 : }
184 1 : child := dir.children[frag]
185 1 : if child == nil {
186 1 : return &os.PathError{
187 1 : Op: "open",
188 1 : Path: fullname,
189 1 : Err: oserror.ErrNotExist,
190 1 : }
191 1 : }
192 1 : if !child.isDir {
193 0 : return &os.PathError{
194 0 : Op: "open",
195 0 : Path: fullname,
196 0 : Err: errors.New("not a directory"),
197 0 : }
198 0 : }
199 1 : dir, fullname = child, remaining
200 : }
201 1 : return nil
202 : }
203 :
204 : // Create implements FS.Create.
205 1 : func (y *MemFS) Create(fullname string) (File, error) {
206 1 : var ret *memFile
207 1 : err := y.walk(fullname, func(dir *memNode, frag string, final bool) error {
208 1 : if final {
209 1 : if frag == "" {
210 0 : return errors.New("pebble/vfs: empty file name")
211 0 : }
212 1 : n := &memNode{}
213 1 : dir.children[frag] = n
214 1 : ret = &memFile{
215 1 : name: frag,
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 : name: sep, // this is the root directory
280 1 : n: dir,
281 1 : fs: y,
282 1 : }
283 1 : return nil
284 1 : }
285 1 : if n := dir.children[frag]; n != nil {
286 1 : ret = &memFile{
287 1 : name: frag,
288 1 : n: n,
289 1 : fs: y,
290 1 : read: true,
291 1 : write: openForWrite,
292 1 : }
293 1 : }
294 : }
295 1 : return nil
296 : })
297 1 : if err != nil {
298 1 : return nil, err
299 1 : }
300 1 : if ret == nil {
301 1 : return nil, &os.PathError{
302 1 : Op: "open",
303 1 : Path: fullname,
304 1 : Err: oserror.ErrNotExist,
305 1 : }
306 1 : }
307 1 : ret.n.refs.Add(1)
308 1 : return ret, nil
309 : }
310 :
311 : // Open implements FS.Open.
312 1 : func (y *MemFS) Open(fullname string, opts ...OpenOption) (File, error) {
313 1 : return y.open(fullname, false /* openForWrite */)
314 1 : }
315 :
316 : // OpenReadWrite implements FS.OpenReadWrite.
317 1 : func (y *MemFS) OpenReadWrite(fullname string, opts ...OpenOption) (File, error) {
318 1 : f, err := y.open(fullname, true /* openForWrite */)
319 1 : pathErr, ok := err.(*os.PathError)
320 1 : if ok && pathErr.Err == oserror.ErrNotExist {
321 1 : return y.Create(fullname)
322 1 : }
323 1 : return f, err
324 : }
325 :
326 : // OpenDir implements FS.OpenDir.
327 1 : func (y *MemFS) OpenDir(fullname string) (File, error) {
328 1 : return y.open(fullname, false /* openForWrite */)
329 1 : }
330 :
331 : // Remove implements FS.Remove.
332 1 : func (y *MemFS) Remove(fullname string) error {
333 1 : return y.walk(fullname, func(dir *memNode, frag string, final bool) error {
334 1 : if final {
335 1 : if frag == "" {
336 0 : return errors.New("pebble/vfs: empty file name")
337 0 : }
338 1 : child, ok := dir.children[frag]
339 1 : if !ok {
340 0 : return oserror.ErrNotExist
341 0 : }
342 1 : if y.windowsSemantics {
343 0 : // Disallow removal of open files/directories which implements
344 0 : // Windows semantics. This ensures that we don't regress in the
345 0 : // ordering of operations and try to remove a file while it is
346 0 : // still open.
347 0 : if n := child.refs.Load(); n > 0 {
348 0 : return oserror.ErrInvalid
349 0 : }
350 : }
351 1 : if len(child.children) > 0 {
352 0 : return errNotEmpty
353 0 : }
354 1 : delete(dir.children, frag)
355 : }
356 1 : return nil
357 : })
358 : }
359 :
360 : // RemoveAll implements FS.RemoveAll.
361 0 : func (y *MemFS) RemoveAll(fullname string) error {
362 0 : err := y.walk(fullname, func(dir *memNode, frag string, final bool) error {
363 0 : if final {
364 0 : if frag == "" {
365 0 : return errors.New("pebble/vfs: empty file name")
366 0 : }
367 0 : _, ok := dir.children[frag]
368 0 : if !ok {
369 0 : return nil
370 0 : }
371 0 : delete(dir.children, frag)
372 : }
373 0 : return nil
374 : })
375 : // Match os.RemoveAll which returns a nil error even if the parent
376 : // directories don't exist.
377 0 : if oserror.IsNotExist(err) {
378 0 : err = nil
379 0 : }
380 0 : return err
381 : }
382 :
383 : // Rename implements FS.Rename.
384 1 : func (y *MemFS) Rename(oldname, newname string) error {
385 1 : var n *memNode
386 1 : err := y.walk(oldname, func(dir *memNode, frag string, final bool) error {
387 1 : if final {
388 1 : if frag == "" {
389 0 : return errors.New("pebble/vfs: empty file name")
390 0 : }
391 1 : n = dir.children[frag]
392 1 : delete(dir.children, frag)
393 : }
394 1 : return nil
395 : })
396 1 : if err != nil {
397 0 : return err
398 0 : }
399 1 : if n == nil {
400 0 : return &os.PathError{
401 0 : Op: "open",
402 0 : Path: oldname,
403 0 : Err: oserror.ErrNotExist,
404 0 : }
405 0 : }
406 1 : return y.walk(newname, func(dir *memNode, frag string, final bool) error {
407 1 : if final {
408 1 : if frag == "" {
409 0 : return errors.New("pebble/vfs: empty file name")
410 0 : }
411 1 : dir.children[frag] = n
412 : }
413 1 : return nil
414 : })
415 : }
416 :
417 : // ReuseForWrite implements FS.ReuseForWrite.
418 0 : func (y *MemFS) ReuseForWrite(oldname, newname string) (File, error) {
419 0 : if err := y.Rename(oldname, newname); err != nil {
420 0 : return nil, err
421 0 : }
422 0 : f, err := y.Open(newname)
423 0 : if err != nil {
424 0 : return nil, err
425 0 : }
426 0 : y.mu.Lock()
427 0 : defer y.mu.Unlock()
428 0 :
429 0 : mf := f.(*memFile)
430 0 : mf.read = false
431 0 : mf.write = true
432 0 : return f, nil
433 : }
434 :
435 : // MkdirAll implements FS.MkdirAll.
436 1 : func (y *MemFS) MkdirAll(dirname string, perm os.FileMode) error {
437 1 : return y.walk(dirname, func(dir *memNode, frag string, final bool) error {
438 1 : if frag == "" {
439 0 : if final {
440 0 : return nil
441 0 : }
442 0 : return errors.New("pebble/vfs: empty file name")
443 : }
444 1 : child := dir.children[frag]
445 1 : if child == nil {
446 1 : dir.children[frag] = &memNode{
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.
554 : type memNode struct {
555 : isDir bool
556 : refs atomic.Int32
557 :
558 : // Mutable state.
559 : // - For a file: data, syncedDate, modTime: A file is only being mutated by a single goroutine,
560 : // but there can be concurrent readers e.g. DB.Checkpoint() which can read WAL or MANIFEST
561 : // files that are being written to. Additionally Sync() calls can be concurrent with writing.
562 : // - For a directory: children and syncedChildren. Concurrent writes are possible, and
563 : // these are protected using MemFS.mu.
564 : mu struct {
565 : sync.Mutex
566 : data []byte
567 : syncedData []byte
568 : modTime time.Time
569 : }
570 :
571 : children map[string]*memNode
572 : syncedChildren map[string]*memNode
573 : }
574 :
575 1 : func newRootMemNode() *memNode {
576 1 : return &memNode{
577 1 : children: make(map[string]*memNode),
578 1 : isDir: true,
579 1 : }
580 1 : }
581 :
582 0 : func (f *memNode) dump(w *bytes.Buffer, level int, name string) {
583 0 : if f.isDir {
584 0 : w.WriteString(" ")
585 0 : } else {
586 0 : f.mu.Lock()
587 0 : fmt.Fprintf(w, "%8d ", len(f.mu.data))
588 0 : f.mu.Unlock()
589 0 : }
590 0 : for i := 0; i < level; i++ {
591 0 : w.WriteString(" ")
592 0 : }
593 0 : w.WriteString(name)
594 0 : if !f.isDir {
595 0 : w.WriteByte('\n')
596 0 : return
597 0 : }
598 0 : if level > 0 { // deal with the fact that the root's name is already "/"
599 0 : w.WriteByte(sep[0])
600 0 : }
601 0 : w.WriteByte('\n')
602 0 : names := make([]string, 0, len(f.children))
603 0 : for name := range f.children {
604 0 : names = append(names, name)
605 0 : }
606 0 : sort.Strings(names)
607 0 : for _, name := range names {
608 0 : f.children[name].dump(w, level+1, name)
609 0 : }
610 : }
611 :
612 0 : func (f *memNode) resetToSyncedState() {
613 0 : if f.isDir {
614 0 : f.children = make(map[string]*memNode)
615 0 : for k, v := range f.syncedChildren {
616 0 : f.children[k] = v
617 0 : }
618 0 : for _, v := range f.children {
619 0 : v.resetToSyncedState()
620 0 : }
621 0 : } else {
622 0 : f.mu.Lock()
623 0 : f.mu.data = slices.Clone(f.mu.syncedData)
624 0 : f.mu.Unlock()
625 0 : }
626 : }
627 :
628 : // memFile is a reader or writer of a node's data. Implements File.
629 : type memFile struct {
630 : name string
631 : n *memNode
632 : fs *MemFS // nil for a standalone memFile
633 : rpos int
634 : wpos int
635 : read, write bool
636 : }
637 :
638 : var _ File = (*memFile)(nil)
639 :
640 1 : func (f *memFile) Close() error {
641 1 : if n := f.n.refs.Add(-1); n < 0 {
642 0 : panic(fmt.Sprintf("pebble: close of unopened file: %d", n))
643 : }
644 : // Set node pointer to nil, to cause panic on any subsequent method call. This
645 : // is a defence-in-depth to catch use-after-close or double-close bugs.
646 1 : f.n = nil
647 1 : return nil
648 : }
649 :
650 1 : func (f *memFile) Read(p []byte) (int, error) {
651 1 : if !f.read {
652 0 : return 0, errors.New("pebble/vfs: file was not opened for reading")
653 0 : }
654 1 : if f.n.isDir {
655 0 : return 0, errors.New("pebble/vfs: cannot read a directory")
656 0 : }
657 1 : f.n.mu.Lock()
658 1 : defer f.n.mu.Unlock()
659 1 : if f.rpos >= len(f.n.mu.data) {
660 1 : return 0, io.EOF
661 1 : }
662 1 : n := copy(p, f.n.mu.data[f.rpos:])
663 1 : f.rpos += n
664 1 : return n, nil
665 : }
666 :
667 1 : func (f *memFile) ReadAt(p []byte, off int64) (int, error) {
668 1 : if !f.read {
669 0 : return 0, errors.New("pebble/vfs: file was not opened for reading")
670 0 : }
671 1 : if f.n.isDir {
672 0 : return 0, errors.New("pebble/vfs: cannot read a directory")
673 0 : }
674 1 : f.n.mu.Lock()
675 1 : defer f.n.mu.Unlock()
676 1 : if off >= int64(len(f.n.mu.data)) {
677 0 : return 0, io.EOF
678 0 : }
679 1 : n := copy(p, f.n.mu.data[off:])
680 1 : if n < len(p) {
681 0 : return n, io.EOF
682 0 : }
683 1 : return n, nil
684 : }
685 :
686 1 : func (f *memFile) Write(p []byte) (int, error) {
687 1 : if !f.write {
688 0 : return 0, errors.New("pebble/vfs: file was not created for writing")
689 0 : }
690 1 : if f.n.isDir {
691 0 : return 0, errors.New("pebble/vfs: cannot write a directory")
692 0 : }
693 1 : f.n.mu.Lock()
694 1 : defer f.n.mu.Unlock()
695 1 : f.n.mu.modTime = time.Now()
696 1 : if f.wpos+len(p) <= len(f.n.mu.data) {
697 1 : n := copy(f.n.mu.data[f.wpos:f.wpos+len(p)], p)
698 1 : if n != len(p) {
699 0 : panic("stuff")
700 : }
701 1 : } else {
702 1 : f.n.mu.data = append(f.n.mu.data[:f.wpos], p...)
703 1 : }
704 1 : f.wpos += len(p)
705 1 :
706 1 : if invariants.Enabled {
707 1 : // Mutate the input buffer to flush out bugs in Pebble which expect the
708 1 : // input buffer to be unmodified.
709 1 : for i := range p {
710 1 : p[i] ^= 0xff
711 1 : }
712 : }
713 1 : return len(p), nil
714 : }
715 :
716 1 : func (f *memFile) WriteAt(p []byte, ofs int64) (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 :
727 1 : for len(f.n.mu.data) < int(ofs)+len(p) {
728 1 : f.n.mu.data = append(f.n.mu.data, 0)
729 1 : }
730 :
731 1 : n := copy(f.n.mu.data[int(ofs):int(ofs)+len(p)], p)
732 1 : if n != len(p) {
733 0 : panic("stuff")
734 : }
735 :
736 1 : return len(p), nil
737 : }
738 :
739 1 : func (f *memFile) Prefetch(offset int64, length int64) error { return nil }
740 1 : func (f *memFile) Preallocate(offset, length int64) error { return nil }
741 :
742 1 : func (f *memFile) Stat() (os.FileInfo, error) {
743 1 : f.n.mu.Lock()
744 1 : defer f.n.mu.Unlock()
745 1 : return &memFileInfo{
746 1 : name: f.name,
747 1 : size: int64(len(f.n.mu.data)),
748 1 : modTime: f.n.mu.modTime,
749 1 : isDir: f.n.isDir,
750 1 : }, nil
751 1 : }
752 :
753 1 : func (f *memFile) Sync() error {
754 1 : if f.fs == nil || !f.fs.strict {
755 1 : return nil
756 1 : }
757 1 : f.fs.mu.Lock()
758 1 : defer f.fs.mu.Unlock()
759 1 : if f.fs.ignoreSyncs {
760 0 : return nil
761 0 : }
762 1 : if f.n.isDir {
763 1 : f.n.syncedChildren = make(map[string]*memNode)
764 1 : for k, v := range f.n.children {
765 1 : f.n.syncedChildren[k] = v
766 1 : }
767 1 : } else {
768 1 : f.n.mu.Lock()
769 1 : f.n.mu.syncedData = slices.Clone(f.n.mu.data)
770 1 : f.n.mu.Unlock()
771 1 : }
772 1 : return nil
773 : }
774 :
775 1 : func (f *memFile) SyncData() error {
776 1 : return f.Sync()
777 1 : }
778 :
779 0 : func (f *memFile) SyncTo(length int64) (fullSync bool, err error) {
780 0 : // NB: This SyncTo implementation lies, with its return values claiming it
781 0 : // synced the data up to `length`. When fullSync=false, SyncTo provides no
782 0 : // durability guarantees, so this can help surface bugs where we improperly
783 0 : // rely on SyncTo providing durability.
784 0 : return false, nil
785 0 : }
786 :
787 1 : func (f *memFile) Fd() uintptr {
788 1 : return InvalidFd
789 1 : }
790 :
791 : // Flush is a no-op and present only to prevent buffering at higher levels
792 : // (e.g. it prevents sstable.Writer from using a bufio.Writer).
793 0 : func (f *memFile) Flush() error {
794 0 : return nil
795 0 : }
796 :
797 : // memFileInfo implements os.FileInfo for a memFile.
798 : type memFileInfo struct {
799 : name string
800 : size int64
801 : modTime time.Time
802 : isDir bool
803 : }
804 :
805 : var _ os.FileInfo = (*memFileInfo)(nil)
806 :
807 0 : func (f *memFileInfo) Name() string {
808 0 : return f.name
809 0 : }
810 :
811 1 : func (f *memFileInfo) Size() int64 {
812 1 : return f.size
813 1 : }
814 :
815 0 : func (f *memFileInfo) Mode() os.FileMode {
816 0 : if f.isDir {
817 0 : return os.ModeDir | 0755
818 0 : }
819 0 : return 0755
820 : }
821 :
822 0 : func (f *memFileInfo) ModTime() time.Time {
823 0 : return f.modTime
824 0 : }
825 :
826 0 : func (f *memFileInfo) IsDir() bool {
827 0 : return f.isDir
828 0 : }
829 :
830 0 : func (f *memFileInfo) Sys() interface{} {
831 0 : return nil
832 0 : }
833 :
834 : type memFileLock struct {
835 : y *MemFS
836 : f File
837 : fullname string
838 : }
839 :
840 1 : func (l *memFileLock) Close() error {
841 1 : if l.y == nil {
842 0 : return nil
843 0 : }
844 1 : l.y.lockedFiles.Delete(l.fullname)
845 1 : l.y = nil
846 1 : return l.f.Close()
847 : }
|