Files
wild-central/internal/storage/storage.go
Paul Payne 88acd437a1 Add resiliency primitives: atomic writes, reconcile mutex, state backup
- Add storage.WriteFileAtomic (temp + rename) and storage.CopyFile helpers
- Convert all 8 production config writers to atomic writes: config/state.yaml,
  dnsmasq, nftables, domains, wireguard (config + secrets + peers + wg0.conf),
  tunnel/cloudflared
- Add sync.Mutex to Reconciler to serialize concurrent Reconcile() calls
  triggered by domain registration goroutines
- Add state.yaml backup (.bak) before every write; LoadState falls back to
  backup if primary is corrupted
- Reconciler refuses to use empty config on corruption (only on first run
  when no state file exists yet)
2026-07-14 11:37:33 +00:00

155 lines
3.8 KiB
Go

package storage
import (
"fmt"
"os"
"path/filepath"
"syscall"
)
// EnsureDir creates a directory with specified permissions if it doesn't exist
func EnsureDir(path string, perm os.FileMode) error {
if err := os.MkdirAll(path, perm); err != nil {
return fmt.Errorf("creating directory %s: %w", path, err)
}
return nil
}
// FileExists checks if a file exists
func FileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// WriteFile writes content to a file with specified permissions
func WriteFile(path string, content []byte, perm os.FileMode) error {
if err := os.WriteFile(path, content, perm); err != nil {
return fmt.Errorf("writing file %s: %w", path, err)
}
return nil
}
// ReadFile reads content from a file
func ReadFile(path string) ([]byte, error) {
content, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading file %s: %w", path, err)
}
return content, nil
}
// Lock represents a file lock
type Lock struct {
file *os.File
path string
}
// AcquireLock acquires an exclusive lock on a file
func AcquireLock(lockPath string) (*Lock, error) {
// Ensure lock directory exists
if err := EnsureDir(filepath.Dir(lockPath), 0755); err != nil {
return nil, err
}
// Open or create lock file
file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, fmt.Errorf("opening lock file %s: %w", lockPath, err)
}
// Acquire exclusive lock with flock
if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
file.Close()
return nil, fmt.Errorf("acquiring lock on %s: %w", lockPath, err)
}
return &Lock{
file: file,
path: lockPath,
}, nil
}
// Release releases the file lock
func (l *Lock) Release() error {
if l.file == nil {
return nil
}
// Release flock
if err := syscall.Flock(int(l.file.Fd()), syscall.LOCK_UN); err != nil {
l.file.Close()
return fmt.Errorf("releasing lock on %s: %w", l.path, err)
}
// Close file
if err := l.file.Close(); err != nil {
return fmt.Errorf("closing lock file %s: %w", l.path, err)
}
l.file = nil
return nil
}
// WithLock executes a function while holding a lock
func WithLock(lockPath string, fn func() error) error {
lock, err := AcquireLock(lockPath)
if err != nil {
return err
}
defer func() { _ = lock.Release() }()
return fn()
}
// WriteFileAtomic writes content to a file atomically via temp + rename.
// If the process crashes mid-write, the original file is untouched.
func WriteFileAtomic(path string, content []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
if err := EnsureDir(dir, 0755); err != nil {
return err
}
tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp.*")
if err != nil {
return fmt.Errorf("creating temp file for %s: %w", path, err)
}
tmpPath := tmp.Name()
if _, err := tmp.Write(content); err != nil {
tmp.Close()
os.Remove(tmpPath)
return fmt.Errorf("writing temp file %s: %w", tmpPath, err)
}
if err := tmp.Chmod(perm); err != nil {
tmp.Close()
os.Remove(tmpPath)
return fmt.Errorf("setting permissions on %s: %w", tmpPath, err)
}
if err := tmp.Close(); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("closing temp file %s: %w", tmpPath, err)
}
if err := os.Rename(tmpPath, path); err != nil {
os.Remove(tmpPath)
return fmt.Errorf("installing %s → %s: %w", tmpPath, path, err)
}
return nil
}
// CopyFile copies a file atomically. Used for creating .bak backups.
func CopyFile(src, dst string) error {
data, err := os.ReadFile(src)
if err != nil {
return fmt.Errorf("reading %s: %w", src, err)
}
return WriteFileAtomic(dst, data, 0644)
}
// EnsureFilePermissions ensures a file has the correct permissions
func EnsureFilePermissions(path string, perm os.FileMode) error {
if err := os.Chmod(path, perm); err != nil {
return fmt.Errorf("setting permissions on %s: %w", path, err)
}
return nil
}