Documentation
¶
Overview ¶
Package statedir keeps the last accepted snapshot and its verified objects in a directory, so a restart serves the last content even when the store is unreachable, and costs one conditional GET (a 304) and no object GET when it is not.
It plugs into the polling flag source through Store.Hooks: the source stays ignorant of the file system. The design in short:
- Layout: VERSION, LOCK, snapshot.json (an envelope: the ETag, the snapshot, the checksums of its objects and a digest of all of it) and objects/<sha256> (content addressed, mode 0600, directory 0700).
- The digest is a check against damage, not against an attacker.
- Every file is written to a temporary file in its own directory, fsynced, renamed and the directory is fsynced. Objects go first and the snapshot last, so the snapshot on disk never names an object that is not there; garbage collection runs after the snapshot rename.
- Everything read back is verified: the snapshot by its digest and every object by its sha256. A file that fails is ignored on its own: a bad object costs one GET, a bad snapshot a cold start. Nothing unverified is ever returned to the reader.
- The writes happen on one background writer fed latest-wins (Store.Run): Store.Hooks Save only queues, so a slow disk never delays a poll. A failed write is reported in the state status, never stops polling and is retried with the next snapshot.
- A directory has one owner at a time: an exclusive advisory lock (flock, on systems that have it) makes a second process fail with ErrLocked. Without the lock two writers can delete each other's objects, and the restore is then partial; nothing is corrupted, because every file is complete or absent and everything read back is verified.
- A directory that is not ours is never touched: a symbolic link, a world-writable directory, foreign files and no VERSION (ErrUnsafe), another layout version (ErrForeignVersion). OpenOrDisable turns those refusals into hooks that only report them, so the relay runs without a cache directory and never fails to start.
- A restart publishes the restored snapshot first: names that were stale when the state was saved come back stale with their old bytes.
All file system access goes through the small FS and Root interfaces, so tests inject failures.
Index ¶
Constants ¶
const ( // ReasonNoSpace is a full disk or an exhausted quota. ReasonNoSpace = "no-space" // ReasonDenied is a permission failure or a read-only file system. ReasonDenied = "denied" // ReasonIO is any other failure of the file system (EIO, a failed fsync or rename). ReasonIO = "io" // ReasonUnsafe is a directory that is not ours any more (a foreign layout version or foreign files). ReasonUnsafe = "unsafe" )
Closed reasons of a failed save, in cachestate.StateStatus.LastSaveError and the metrics.
const ( // DisabledUnsafe is [ErrUnsafe]: a symbolic link, a file, a world-writable or unusable directory, or a // directory that holds foreign files and no VERSION. DisabledUnsafe = "unsafe" // DisabledLocked is [ErrLocked]: another process uses the directory. DisabledLocked = "locked" // DisabledForeignVersion is [ErrForeignVersion]. DisabledForeignVersion = "foreign-version" // DisabledParentSync is [ErrParentSync]: a flush of a parent of the directory that was created failed. DisabledParentSync = "parent-sync" // DisabledError is any other failure to open the directory. DisabledError = "error" )
Closed reasons of a cache directory that is not used, in cachestate.StateStatus.DisabledReason.
Variables ¶
var ( // ErrLocked is returned when another process (or another store) holds the directory. ErrLocked = errors.New("statedir: directory is in use by another owner") // ErrUnsafe is returned for a directory that the process cannot own: a symlink, a file, a directory of // another user, or one whose mode cannot be made private. ErrUnsafe = errors.New("statedir: directory is not safe to use") // ErrNoDir is returned when [Config.Dir] is empty. ErrNoDir = errors.New("statedir: no directory configured") // ErrForeignVersion is returned when VERSION names another layout version: the directory belongs to another // version of the software. Nothing is read from it, written to it or deleted from it. ErrForeignVersion = errors.New("statedir: directory has another layout version") // ErrNotRegular is what [Root.ReadFile] returns for a name that is not a regular file (a FIFO, a device, a // directory, a symbolic link): such a file is discarded and never opened. ErrNotRegular = errors.New("statedir: not a regular file") // ErrFileTooLarge is what [Root.ReadFile] returns for a file above its limit: it is not read. ErrFileTooLarge = errors.New("statedir: file above its limit") // ErrParentSync is returned by [OSFS.Open] when the flush of a parent of a directory it created failed (not for lack // of permission): the flush is retried by the next Open. ErrParentSync = errors.New("statedir: the parent directory could not be flushed") )
Errors of opening a cache directory.
Functions ¶
func LockFileExclusive ¶
LockFileExclusive takes a non-blocking exclusive flock; the kernel drops it when the process ends, so a crash leaves no stale lock.
Types ¶
type Config ¶
type Config struct {
// FS is the file system; nil is the real one ([NewOSFS]).
FS FS
// Logger receives the messages of the store; nil discards. It logs closed codes, never paths or contents.
Logger *slog.Logger
// Dir is the cache directory. Required. A directory that does not exist is created with mode 0700. See
// [OSFS] for the rules of an existing one.
Dir string
// MaxBytes bounds the bytes of objects on disk (the state file comes on top). Zero is
// [cachestate.DefaultMaxTotalBytes], the cap on the current objects of the reader. When the current
// objects do not fit, the stale ones are dropped first and then the current ones are kept in this order:
// the contents already on disk are kept first and the rest of the budget goes to the new ones, smallest first;
// such a save is a partial save, not an error.
MaxBytes int64
// MaxSnapshotBytes, MaxObjectBytes and MaxObjects bound what is read back (use the limits of the reader).
// Zero selects [cachestate.DefaultMaxSnapshotBytes], [cachestate.DefaultMaxObjectBytes] and
// [controlplane.DefaultMaxObjects]. A file above its bound is discarded without being read.
MaxSnapshotBytes int64
MaxObjectBytes int64
MaxObjects int
}
Config configures a Store.
type FS ¶
type FS interface {
// Open prepares dir (creating it with mode 0700 when it does not exist) and returns the root of it. It
// returns [ErrUnsafe] for a directory the process cannot own.
Open(dir string) (Root, error)
}
FS opens a cache directory. NewOSFS is the real one; tests wrap it or replace it to inject failures.
type OSFS ¶
type OSFS struct {
// SyncDir flushes the entries of a directory, by its path: it is called for the parent of each directory that
// Open creates. Nil is the flush of the platform. Set it for a file system that refuses to flush a directory.
SyncDir func(string) error
// FlushDir flushes the entries of an open directory, for [Root.SyncDir]. Nil is the flush of the platform
// (which does nothing on Windows). Set it for a file system that refuses to flush a directory.
FlushDir func(*os.File) error
// LockFile takes the exclusive lock on the open lock file of the cache directory, without waiting: it returns
// [ErrLocked] when another owner holds it. Nil is [LockFileExclusive]. Set it to wrap the platform lock, for
// example to log or to delay it.
LockFile func(*os.File) error
// contains filtered or unexported fields
}
OSFS is the file system of the process, on os.Root: a name cannot escape the directory through a symlink. A directory is accepted when it is not a symbolic link, is not world-writable, and the process can read, write and lock it. Its owner does not matter: a volume that Kubernetes mounts with fsGroup is owned by root and group-writable. A directory that does not exist is created with mode 0700; an existing one keeps its mode.
func (OSFS) Open ¶
Open implements FS. A directory that Open creates is made durable: the parent of each directory it created is flushed, top down, so the path survives a power loss with the first save. A flush that fails is remembered and retried by the next Open of the same directory (an existing path does not mean its entry is durable), and Open returns ErrParentSync until it succeeds. A parent that cannot be opened for the flush because of permissions is skipped: the cache directory is a cache, so it is used, and the root reports cachestate.ParentSyncSkipped (after a power loss the directory entry itself may be missing, and the relay then starts as on a first run).
type Root ¶
type Root interface {
// Lock takes the exclusive lock of the directory without waiting; it returns [ErrLocked] when it is held. The
// lock is released by calling release, which also closes the lock file so that the file can be removed (a file
// that is open cannot be removed on every system), by Close, and by the end of the process. created tells that
// this call made the lock file (it did not exist when the attempt that took the lock opened it): the lock
// operation itself decides, never an earlier look at the directory, because another opener may remove the file
// between a look and the lock.
Lock() (release func() error, created bool, err error)
// ReadFile returns the content of a regular file of at most limit bytes. A missing file is [fs.ErrNotExist],
// a name that is not a regular file [ErrNotRegular], a larger file [ErrFileTooLarge]; none of them is opened
// past its type and size check, and the read itself is limited.
ReadFile(name string, limit int64) ([]byte, error)
// Lstat returns the information of a name without following a symlink.
Lstat(name string) (fs.FileInfo, error)
// ReadDir returns the names of a directory, in no particular order.
ReadDir(name string) ([]string, error)
// RootWriter changes the directory.
RootWriter
// Close releases the lock and the directory.
Close() error
// RootReport states how the lock and the flush of the directory went.
RootReport
}
Root is an open cache directory. Names are slash separated and relative to the directory; none may leave it.
type RootReport ¶
type RootReport interface {
// Exclusive tells whether the lock is really held, so the store has the directory to itself. A root that cannot say
// returns false: it is not trusted with it.
Exclusive() bool
// UnlinkWhileLocked tells how a lock file is removed: while the lock is still held (Unix: the standard way, with the
// check of the opener that the file it locked is still at the path), or after it was released and closed (Windows,
// which cannot remove an open file, and has no lock to protect).
UnlinkWhileLocked() bool
// ParentSync tells how the flush of the parents of a created directory went: [cachestate.ParentSyncSkipped]
// when it was skipped, empty otherwise.
ParentSync() string
}
RootReport is the part of Root that tells how the lock and the flush of the parents of the directory went.
type RootWriter ¶
type RootWriter interface {
// Create creates a new file of mode 0600 for writing; it fails when the name exists.
Create(name string) (File, error)
// Rename replaces newname by oldname atomically.
Rename(oldname, newname string) error
// Remove removes a file.
Remove(name string) error
// MkdirAll creates a directory of mode 0700 and its parents.
MkdirAll(name string) error
// SyncDir flushes the entries of a directory to disk.
SyncDir(name string) error
}
RootWriter is the part of Root that changes the directory.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is a cache directory open for use. Build it with New (or OpenOrDisable), give Store.Hooks to the reader, run Store.Run on a goroutine, and call Store.Close after Run returned.
func New ¶
New opens and locks the cache directory and checks that it is ours. It does not read the state: that is Store.Hooks Restore. The errors tell the caller what to do (see OpenOrDisable):
- ErrUnsafe: a symbolic link, a file, a world-writable directory, a directory the process cannot read, write or lock, or a directory that has no VERSION and holds anything but our LOCK and temporary files. Nothing was written.
- ErrLocked: another process or store holds the directory.
- ErrForeignVersion: VERSION names another layout version. Nothing was read, written or deleted.
- ErrNoDir: no directory configured.
func OpenOrDisable ¶
func OpenOrDisable(cfg Config) (*Store, cachestate.Hooks, string)
OpenOrDisable is New with the policy the relay uses: when the directory is refused (ErrUnsafe, ErrLocked, ErrForeignVersion, or any other failure) the relay runs without a cache directory and never fails to start. It logs once at error level, and returns hooks that only report the refusal in the status (cachestate.StateStatus.Restore is cachestate.RestoreDisabled and DisabledReason is one of the Disabled* codes), so the restore metric shows it. The store is nil then, and the reason is not empty.
func (*Store) Close ¶
Close releases the directory and its lock. Call it after Store.Run returned. A second call does nothing.
func (*Store) Flush ¶
Flush returns when the writer is done with everything saved before the call: written, failed (the failure is in cachestate.StateStatus: Flush does not report it) or replaced by a newer snapshot. It needs Store.Run running; ctx bounds the wait.
func (*Store) Hooks ¶
func (s *Store) Hooks() cachestate.Hooks
Hooks returns the hooks of the reader: Restore, Save and StateStatus.