core

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package core implements the shared file storage engine used by protocol exports.

Index

Constants

This section is empty.

Variables

View Source
var ErrHistoryDisabled = errors.New("file history is disabled")

Functions

func ControlSocketPath

func ControlSocketPath(mountpoint string) (string, error)

ControlSocketPath returns the per-mount diagnostics socket used by the CLI. A hash avoids Unix socket path length limits and keeps separate mounts independent even when their mountpoint names are similar.

func Errno

func Errno(err error) syscall.Errno

Errno maps storage failures to the corresponding operating-system error.

Types

type AttrUpdate

type AttrUpdate struct {
	Size    *int64
	Mode    *uint32
	UID     *uint32
	GID     *uint32
	ModTime *time.Time
}

AttrUpdate changes only the fields whose pointers are non-nil.

type Config

type Config = option.Config

Config is the protocol-independent storage configuration from fs/option.

type File

type File struct {
	// contains filtered or unexported fields
}

File exposes the shared chunk/cache/writeback engine without a FUSE mount. Share one File between users of an inode so unstaged writes remain coherent. The owner must stop using the File before closing its FileSystem.

func (*File) Close

func (f *File) Close(ctx context.Context) error

Close waits for backend persistence. A failed close may be retried.

func (*File) CloseLocal

func (f *File) CloseLocal(ctx context.Context) error

CloseLocal closes the handle after its data and metadata are recoverable. With a raw cache, encoding and backend uploads remain owned by FileSystem; without that cache or with Config.SyncBackend this waits for the backend. A failed close may be retried.

func (*File) Discard

func (f *File) Discard(ctx context.Context, off, length int64) error

Discard makes a range read as zero. Whole chunks lose their mappings; partial chunks retain bytes outside the discarded range. It never deletes shared immutable backend objects. Durability is established by Sync.

func (*File) Inode

func (f *File) Inode() uint64

func (*File) ReadAt

func (f *File) ReadAt(ctx context.Context, p []byte, off int64) (int, error)

func (*File) SetAttr

func (f *File) SetAttr(ctx context.Context, update AttrUpdate) (meta.Entry, error)

SetAttr orders attribute changes against this File's pending writes. Callers sharing an inode must share the File rather than modifying metadata directly.

func (*File) Stat

func (f *File) Stat(ctx context.Context) (meta.Entry, error)

Stat includes this File's buffered writes, even without a raw writeback cache. Chunk references are omitted so checking the size does not copy a manifest.

func (*File) Sync

func (f *File) Sync(ctx context.Context, backend bool) error

Sync makes all writes on this shared file durable. backend=false may stop at recoverable local raw storage; backend=true also waits for encoding/upload. Config.SyncBackend establishes a minimum that backend=false cannot weaken.

func (*File) Truncate

func (f *File) Truncate(ctx context.Context, size int64) error

Truncate changes the logical size, preserving pending writes before the new end and making any extension read as zero. It does not change a user's offset.

func (*File) WriteAt

func (f *File) WriteAt(ctx context.Context, p []byte, off int64) (int, error)

type FileReadResult

type FileReadResult struct {
	File   *os.File
	Offset int64
	Length int
}

FileReadResult owns a read-only descriptor to an immutable range. Unlinking the source name does not affect the result's lifetime.

func (*FileReadResult) Bytes

func (r *FileReadResult) Bytes(dest []byte) ([]byte, syscall.Errno)

func (*FileReadResult) Done

func (r *FileReadResult) Done()

func (*FileReadResult) Seekable

func (r *FileReadResult) Seekable() (uintptr, int64, int)

func (*FileReadResult) Size

func (r *FileReadResult) Size() int

type FileSystem

type FileSystem struct {
	// contains filtered or unexported fields
}

FileSystem is a persistent chunk-backed namespace shared by file and block exports.

func New

func New(config Config, options ...option.Option) (filesystem *FileSystem, err error)

New applies shared options, validates the resulting config and starts the storage engine. Configure it once, then select a FUSE, Afero or blk export.

func (*FileSystem) Attr

func (f *FileSystem) Attr(inode uint64) (meta.Entry, error)

Attr includes mutable raw writes that have not yet reached metadata.

func (*FileSystem) CheckpointFile added in v1.0.2

func (f *FileSystem) CheckpointFile(ctx context.Context, inode uint64, label string) (meta.HistoryVersion, error)

CheckpointFile saves the current complete file/directory image. Ordinary successful history writes have already drained every handle to backend.

func (*FileSystem) CheckpointTree added in v1.0.2

func (f *FileSystem) CheckpointTree(ctx context.Context, inode uint64, label string, visit func(meta.HistoryVersion) error) error

CheckpointTree visits the current subtree in bounded directory pages. The caller must quiesce all exports; each image is durable before visit is called. There is no single tree version ID or atomic tree checkpoint.

func (*FileSystem) ChunkSize

func (f *FileSystem) ChunkSize() int

func (*FileSystem) Close

func (f *FileSystem) Close() error

Close persists local writes and stops workers. With raw writeback, call Sync first to also drain backend uploads. Release FUSE handles before closing.

func (*FileSystem) CreateFile

func (f *FileSystem) CreateFile(ctx context.Context, parent uint64, name string, size int64) (*File, error)

CreateFile creates a sparse file: unwritten ranges do not allocate chunks.

func (*FileSystem) DirectoryPageSize added in v1.0.1

func (f *FileSystem) DirectoryPageSize() int

DirectoryPageSize is the bounded page shared by FUSE and Afero enumeration.

func (*FileSystem) Format added in v1.0.1

func (f *FileSystem) Format() fsformat.Volume

Format returns the versioned structural format confirmed when the engine was opened. Compression is selected by each chunk reference's codec.

func (*FileSystem) HasWriteback

func (f *FileSystem) HasWriteback() bool

func (*FileSystem) HistoryEnabled added in v1.0.2

func (f *FileSystem) HistoryEnabled() bool

func (*FileSystem) HistoryVersions added in v1.0.2

func (f *FileSystem) HistoryVersions(ctx context.Context, q meta.HistoryQuery) ([]meta.HistoryVersion, error)

HistoryVersions can read retained records even when automatic recording is off.

func (*FileSystem) Logs

func (f *FileSystem) Logs(after uint64, limit int, errorsOnly bool, pathFilter string) LogSnapshot

Logs returns recent events after a cursor. A zero cursor returns the tail.

func (*FileSystem) Namespace

func (f *FileSystem) Namespace() *meta.Namespace

Namespace is the authoritative metadata view shared by storage frontends.

func (*FileSystem) Open

func (f *FileSystem) Open(inode uint64) (*Handle, error)

Open creates a handle for an existing regular-file inode.

func (*FileSystem) OpenFile

func (f *FileSystem) OpenFile(ctx context.Context, parent uint64, name string) (*File, error)

func (*FileSystem) RecordFuseMetadata added in v1.0.1

func (f *FileSystem) RecordFuseMetadata(operation string)

RecordFuseMetadata counts one supported metadata callback without per-name allocations or logging. Calls handled inside go-fuse itself are not included.

func (*FileSystem) Remove

func (f *FileSystem) Remove(ctx context.Context, inode uint64) error

Remove retires raw data only after the namespace deletion is durable. Files without chunk references do not pin cache data, so their namespace update can stay in the normal asynchronous metadata commit path without a per-unlink fsync barrier.

func (*FileSystem) Rename

func (f *FileSystem) Rename(ctx context.Context, inode, newParent uint64, newName string) error

Rename atomically replaces a compatible destination and retires its quota and raw-cache references. Frontends must order this operation against their own open handles: flush mutable source manifests and do not replace an open destination unless the frontend implements detached-inode lifetime.

func (*FileSystem) RestoreHistory added in v1.0.2

func (f *FileSystem) RestoreHistory(ctx context.Context, o HistoryRestoreOptions) (result HistoryRestoreResult, err error)

RestoreHistory restores a file or recursively restores saved descendants at a cutoff. Each file is atomically published; the tree is NOT one transaction. It never deletes unselected paths. Completed/Items report progress on error. Existing directories are updated in place to preserve their children. Selection and namespace/quota checks finish before the first mutation. Full selected images are spooled to a private temporary file so retention triggered by protecting replaced targets cannot prune a later source out of the plan.

func (*FileSystem) RestoreVersion added in v1.0.2

func (f *FileSystem) RestoreVersion(ctx context.Context, id, parent uint64, name string, replace bool) (meta.Entry, error)

RestoreVersion publishes a saved file image with a NEW inode. Stop/detach FUSE, Afero and NBD exports and their handles before using this maintenance API; it does not invalidate kernel pages or frontend handle caches. The CLI holds the offline storage lock. A replace captures the displaced target first. A saved directory restores that directory only, not a recursive tree. An existing compatible directory keeps its inode and children while attributes are restored, with a protected preimage just like a replaced file.

func (*FileSystem) SetAttr

func (f *FileSystem) SetAttr(ctx context.Context, inode uint64, update AttrUpdate) (meta.Entry, error)

SetAttr preserves pending writes and retires truncated raw references through the same durable metadata path used by regular writes.

func (*FileSystem) Snapshot added in v1.0.1

func (f *FileSystem) Snapshot(ctx context.Context, output io.Writer) error

Snapshot implements meta.Snapshotter. The resulting bbolt image is a standalone recovery point: every staged raw reference is uploaded and rewritten in the copy only. Mutable RAM writes must first be fsynced to be included. New writes and live manifests continue independently.

func (*FileSystem) StartDiagnostics

func (f *FileSystem) StartDiagnostics(path string) error

StartDiagnostics exposes the shared storage diagnostics without mounting FUSE. Use the same path with compactfs stat/log/sync. Close stops the server.

func (*FileSystem) StatsSnapshot

func (f *FileSystem) StatsSnapshot() Stats

StatsSnapshot returns counters without draining the writeback queues.

func (*FileSystem) Sync

func (f *FileSystem) Sync(ctx context.Context) error

Sync flushes all mutable tails and waits for backend completion. Ordinary fsync in local mode stops at the durable NVMe cache instead.

type FuseMetadataStats added in v1.0.1

type FuseMetadataStats struct {
	LookupRequests      uint64 `json:"lookup_requests"`
	GetattrRequests     uint64 `json:"getattr_requests"`
	OpenDirRequests     uint64 `json:"opendir_requests"`
	ReadDirRequests     uint64 `json:"readdir_requests"`
	ReadDirPlusRequests uint64 `json:"readdirplus_requests"`
	GetXattrRequests    uint64 `json:"getxattr_requests"`
}

FuseMetadataStats counts requests delivered by go-fuse to the protocol adapter. Internal LOOKUPs used to populate READDIRPLUS are not counted as independent kernel LOOKUPs. Other exports leave these protocol-specific counters at zero.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle owns one open file's mutable I/O state. Protocol adapters translate its read results and errors; the shared engine owns write ordering and sync.

func (*Handle) Flush

func (h *Handle) Flush(ctx context.Context) syscall.Errno

func (*Handle) Fsync

func (h *Handle) Fsync(ctx context.Context) syscall.Errno

func (*Handle) Read

func (h *Handle) Read(ctx context.Context, dest []byte, off int64) (ReadResult, syscall.Errno)

func (*Handle) Release

func (h *Handle) Release(ctx context.Context) syscall.Errno

func (*Handle) Write

func (h *Handle) Write(ctx context.Context, data []byte, off int64) (uint32, syscall.Errno)

type HistoryConfig added in v1.0.2

type HistoryConfig = option.HistoryConfig

type HistoryIOStats added in v1.0.2

type HistoryIOStats struct {
	Mode                string `json:"mode"`
	JournalCodec        string `json:"journal_codec,omitempty"`
	JournalBytes        int64  `json:"journal_bytes"`
	JournalLogicalBytes int64  `json:"journal_logical_bytes"`
	JournalLimit        int64  `json:"journal_limit"`
	BufferedWrites      int    `json:"buffered_writes"`
	EncodeBufferBytes   int    `json:"encode_buffer_bytes"`
	Checkpoints         int64  `json:"checkpoints"`
	CheckpointNanos     int64  `json:"checkpoint_nanos"`
	BackendWaitNanos    int64  `json:"backend_wait_nanos"`
	PackNanos           int64  `json:"pack_nanos"`
	MetadataNanos       int64  `json:"metadata_nanos"`
	ResetNanos          int64  `json:"reset_nanos"`
}

HistoryIOStats separates local log space and work from backend chunk metrics.

type HistoryRestoreItem added in v1.0.2

type HistoryRestoreItem struct {
	Version uint64    `json:"version"`
	Time    time.Time `json:"time"`
	Path    string    `json:"path"`
	To      string    `json:"to"`
	Kind    meta.Kind `json:"kind"`
	Size    int64     `json:"size"`
	Inode   uint64    `json:"inode,omitempty"` // filled only after successful apply
}

type HistoryRestoreOptions added in v1.0.2

type HistoryRestoreOptions struct {
	Path      string
	At        time.Time
	To        string // defaults to Path
	Recursive bool
	Replace   bool
	Parents   bool // allow creating ancestors outside the selected tree
	DryRun    bool
	PlanBytes int64  // estimated summary budget; zero selects 64 MiB
	TempDir   string // selected images are spooled here before any replacement
}

HistoryRestoreOptions selects independently saved images, not a namespace snapshot. For each saved path, the greatest Time <= At wins (then greatest ID). Newer-only paths and paths without retained images are left untouched. Stop all exports and handles before calling RestoreHistory, even for DryRun.

type HistoryRestoreResult added in v1.0.2

type HistoryRestoreResult struct {
	Path      string               `json:"path"`
	To        string               `json:"to"`
	At        time.Time            `json:"at"`
	DryRun    bool                 `json:"dry_run"`
	Completed int                  `json:"completed"`
	Items     []HistoryRestoreItem `json:"items"`
}

type LogEntry

type LogEntry struct {
	Seq           uint64    `json:"seq"`
	Time          time.Time `json:"time"`
	Kind          string    `json:"kind"`
	Operation     string    `json:"operation"`
	Path          string    `json:"path,omitempty"`
	Inode         uint64    `json:"inode,omitempty"`
	Offset        int64     `json:"offset,omitempty"`
	Bytes         int64     `json:"bytes,omitempty"`
	DurationNanos int64     `json:"duration_nanos,omitempty"`
	Error         string    `json:"error,omitempty"`
}

LogEntry is one recent write-back or FUSE error event. The ring is kept in memory so diagnostics never turn a high-throughput mount into a synchronous log writer.

type LogSnapshot

type LogSnapshot struct {
	Entries []LogEntry `json:"entries"`
	NextSeq uint64     `json:"next_seq"`
	Dropped uint64     `json:"dropped"`
}

LogSnapshot is returned by the /logs endpoint. NextSeq is the cursor to use in a later request; it advances even when filters hide all returned events.

type MemoryStats added in v1.0.1

type MemoryStats struct {
	HeapAlloc    uint64 `json:"heap_alloc"`
	HeapObjects  uint64 `json:"heap_objects"`
	TotalAlloc   uint64 `json:"total_alloc"`
	NumGC        uint32 `json:"num_gc"`
	PauseTotalNS uint64 `json:"pause_total_ns"`
	StagedInodes int    `json:"staged_inodes"`
}

MemoryStats distinguishes Go heap growth from the process RSS reported by the OS. It includes all Go packages in this daemon, not just metadata.

type MetadataBackupConfig added in v1.0.1

type MetadataBackupConfig = option.MetadataBackupConfig

MetadataBackupConfig configures shared automatic backend snapshots.

type RawRefillStats

type RawRefillStats struct {
	CapacityBytes int64 `json:"capacity_bytes"`
	PendingBytes  int64 `json:"pending_bytes"`
	Pending       int   `json:"pending"`
	Submitted     int64 `json:"submitted"`
	Completed     int64 `json:"completed"`
	Bytes         int64 `json:"bytes"`
	Skipped       int64 `json:"skipped"`
	Errors        int64 `json:"errors"`
}

RawRefillStats counts optional SSD fills independently of durable writes. PendingBytes includes the active fill and every queued immutable raw slice.

type ReadConfig

type ReadConfig = option.ReadConfig

ReadConfig configures the shared decoded cache and raw refill.

type ReadResult

type ReadResult interface {
	Size() int
	Bytes([]byte) ([]byte, syscall.Errno)
	Done()
}

ReadResult owns immutable bytes or an open file range. The caller must call Done after consuming the result; file-backed replies can be sent without first copying the range into an application buffer.

type Stats

type Stats struct {
	MountPoint             string              `json:"mount_point"`
	PID                    int                 `json:"pid"`
	StartedAt              time.Time           `json:"started_at"`
	UpdatedAt              time.Time           `json:"updated_at"`
	UptimeNanos            int64               `json:"uptime_nanos"`
	CodecName              string              `json:"codec_name,omitempty"`
	MetadataEngine         string              `json:"metadata_engine"`
	HashAlgorithm          string              `json:"hash_algorithm"`
	CodecHealth            string              `json:"codec_health,omitempty"`
	CodecWorker            *codec.WorkerStatus `json:"codec_worker,omitempty"`
	SyncMode               string              `json:"sync_mode"`
	Writeback              *writer.Stats       `json:"writeback,omitempty"`
	WriteBufferBytes       int64               `json:"write_buffer_bytes"`
	WriteBufferPoolBytes   int64               `json:"write_buffer_pool_bytes"`
	WriteBufferAllocations int64               `json:"write_buffer_allocations"`
	WriteBufferReuses      int64               `json:"write_buffer_reuses"`
	WriteBufferZeroBytes   int64               `json:"write_buffer_zero_bytes"`
	RawPendingJobs         int64               `json:"raw_pending_jobs"`
	RawPendingBytes        int64               `json:"raw_pending_bytes"`
	RawErrors              int64               `json:"raw_errors"`
	RawRefill              *RawRefillStats     `json:"raw_refill,omitempty"`
	ReadCache              *reader.Stats       `json:"read_cache,omitempty"`
	MetadataBackup         *meta.BackupStats   `json:"metadata_backup,omitempty"`
	History                *HistoryIOStats     `json:"history,omitempty"`
	Memory                 MemoryStats         `json:"memory"`
	FuseMetadata           FuseMetadataStats   `json:"fuse_metadata"`

	FuseOperations    int64 `json:"fuse_operations"`
	ReadOperations    int64 `json:"read_operations"`
	ReadBytes         int64 `json:"read_bytes"`
	ReadNanos         int64 `json:"read_nanos"`
	WriteOperations   int64 `json:"write_operations"`
	WriteBytes        int64 `json:"write_bytes"`
	WriteNanos        int64 `json:"write_nanos"`
	FlushOperations   int64 `json:"flush_operations"`
	FlushNanos        int64 `json:"flush_nanos"`
	FsyncOperations   int64 `json:"fsync_operations"`
	FsyncNanos        int64 `json:"fsync_nanos"`
	ReleaseOperations int64 `json:"release_operations"`
	ReleaseNanos      int64 `json:"release_nanos"`

	QueueSubmittedJobs int64 `json:"queue_submitted_jobs"`
	QueueCompletedJobs int64 `json:"queue_completed_jobs"`
	QueuePendingJobs   int64 `json:"queue_pending_jobs"`
	QueuePendingBytes  int64 `json:"queue_pending_bytes"`
	QueueErrors        int64 `json:"queue_errors"`
	ChunkPutOperations int64 `json:"chunk_put_operations"`
	ChunkPutBytes      int64 `json:"chunk_put_bytes"`
	ChunkPutNanos      int64 `json:"chunk_put_nanos"`
	ChunkPutErrors     int64 `json:"chunk_put_errors"`

	PutOperations           int64 `json:"put_operations"`
	PutBytes                int64 `json:"put_bytes"`
	PutNanos                int64 `json:"put_nanos"`
	PutErrors               int64 `json:"put_errors"`
	EncodeOperations        int64 `json:"encode_operations"`
	EncodeBytes             int64 `json:"encode_bytes"`
	EncodeNanos             int64 `json:"encode_nanos"`
	EncodeErrors            int64 `json:"encode_errors"`
	EncodeBufferAllocations int64 `json:"encode_buffer_allocations"`
	EncodeBufferReuses      int64 `json:"encode_buffer_reuses"`
	EncodeBufferPoolBytes   int64 `json:"encode_buffer_pool_bytes"`
	BackendStatOperations   int64 `json:"backend_stat_operations"`
	BackendStatNanos        int64 `json:"backend_stat_nanos"`
	BackendStatErrors       int64 `json:"backend_stat_errors"`
	BackendPutOperations    int64 `json:"backend_put_operations"`
	BackendPutBytes         int64 `json:"backend_put_bytes"`
	BackendPutNanos         int64 `json:"backend_put_nanos"`
	BackendPutErrors        int64 `json:"backend_put_errors"`
	BackendImportOperations int64 `json:"backend_import_operations"`
	BackendImportBytes      int64 `json:"backend_import_bytes"`
	BackendImportNanos      int64 `json:"backend_import_nanos"`
	BackendImportFallbacks  int64 `json:"backend_import_fallbacks"`
	BackendRangeOperations  int64 `json:"backend_range_operations"`
	BackendRangeBytes       int64 `json:"backend_range_bytes"`
	BackendGetOperations    int64 `json:"backend_get_operations"`
	BackendGetBytes         int64 `json:"backend_get_bytes"`
	BackendGetNanos         int64 `json:"backend_get_nanos"`
	BackendGetErrors        int64 `json:"backend_get_errors"`
	CacheGetOperations      int64 `json:"cache_get_operations"`
	CacheGetBytes           int64 `json:"cache_get_bytes"`
	CacheGetNanos           int64 `json:"cache_get_nanos"`
	CacheGetErrors          int64 `json:"cache_get_errors"`
	CacheHits               int64 `json:"cache_hits"`
	CacheMisses             int64 `json:"cache_misses"`
	CachePutOperations      int64 `json:"cache_put_operations"`
	CachePutBytes           int64 `json:"cache_put_bytes"`
	CachePutNanos           int64 `json:"cache_put_nanos"`
	CachePutErrors          int64 `json:"cache_put_errors"`
	DecodeOperations        int64 `json:"decode_operations"`
	DecodeBytes             int64 `json:"decode_bytes"`
	DecodeNanos             int64 `json:"decode_nanos"`
	DecodeErrors            int64 `json:"decode_errors"`

	LastError   string    `json:"last_error,omitempty"`
	LastErrorAt time.Time `json:"last_error_at,omitempty"`
}

Stats is a cumulative snapshot of one mounted filesystem. Byte counters are logical bytes unless their name says stored or compressed; durations are in nanoseconds. The CLI turns these counters into rates for human output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL