Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions .github/workflows/scripts/copywrite.hcl

This file was deleted.

40 changes: 0 additions & 40 deletions .golangci.yaml

This file was deleted.

2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ lint: vet
# locally install build dependencies
[group('build')]
init:
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.4
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A library for atomic filesystem operations in Go.

# Overview

The `cattlecloud.net/go/atomicfs` module provides a package for performing atomic
The `cattlecloud.net/go/atomicfs/v2` module provides a package for performing atomic
filesystem operations.

#### Reading material
Expand All @@ -25,18 +25,22 @@ go get cattlecloud.net/go/atomicfs@latest
```

```go
import "cattlecloud.net/go/atomicfs"
import "cattlecloud.net/go/atomicfs/v2"
```

#### Examples

Written files default to mode `0660` (read-write for the owner and group).
Pass `atomicfs.WithMode` to override it:

```go
writer := atomicfs.NewFileWriter(atomicfs.Options{
TmpDirectory: "/tmp",
Mode: 0600,
})
writer := atomicfs.New(
atomicfs.WithTempDir("/tmp"),
atomicfs.WithMode(0600), // custom file mode
)

_ = writer.Write(input, output)
input := strings.NewReader("hello, world")
_ = writer.WriteFile("/path/to/output.txt", input)
```

# Contributing
Expand Down
185 changes: 79 additions & 106 deletions atomicfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,108 +12,80 @@ import (
"os"
"path/filepath"
"strings"
"syscall"

"cattlecloud.net/go/atomicfs/fs"
"cattlecloud.net/go/atomicfs/sys"
)

// A FileWriter is used to read content from a source and write it to a
// destination file, or die trying without producing corrupt data where the
// destination file should have been.
// A Writer writes the contents of an io.Reader to a destination file
// atomically, or fails without leaving corrupt data in place of the
// destination file.
//
// The primary design goal of a FileWriter is correctness and reliability.
// The primary design goal of a Writer is correctness and reliability.
//
// Performance is not a consideration.
type FileWriter interface {
// WriteFile will write the contents of the io.Reader into a file at the
// given destination filepath.
WriteFile(string, io.Reader) error
}

// Options are used to configure the behavior of a FileWriter when it is used
// to write a file.
type Options struct {
// TmpDirectory is where tmp files are generated during
// the process of writing a file in preparation for executing
// an atomic rename. Because of this, TmpDirectory *MUST* be on
// the same filesystem device as the destination file being
// written, otherwise, errors will be returned during the Write.
TmpDirectory string

// TmpExtension is used to demarcate the tmp files generated
// during the Write operation from other normal files. The
// extension is appended to the end of the filename of the
// destination file being written.
TmpExtension string

// Mode is the file mode of the destination file to be written.
// If no Mode is provided, write only permissions for the user
// are used (i.e. 0200).
Mode os.FileMode

// FS is the underlying filesystem implementation to be used
// for writing files to disk. Typically this should be left
// nil, as then fs.FileSystem is used, which in turn is
// implemented using the file operations defined in the os
// package.
FS fs.FileSystem

// Sys is the underlying syscall implementation to be used,
// in this case only for stat-ing files. Typically this should
// be left nil, as then sys.Syscall is used, which in turn is
// implemented using the syscall implementation provided by
// the go runtime.
Sys sys.Syscall
type Writer struct {
tempDir string
tempExt string
mode os.FileMode
}

// New creates a new FileWriter backed by the configuration settings in the
// provided Options. Creating a FileWriter always succeeds, replacing empty
// options with sane defaults.
func New(options Options) FileWriter {
tmpExt := strings.TrimPrefix(options.TmpExtension, ".")
if tmpExt == "" {
tmpExt = "tmp"
}
// An Option configures the behavior of a Writer.
type Option func(*Writer)

tmpDir := options.TmpDirectory
if tmpDir == "" {
tmpDir = os.TempDir()
// WithTempDir sets the directory where temporary files are created during the
// process of writing a file in preparation for an atomic rename.
//
// The temp dir must be on the same filesystem device as the destination file,
// otherwise errors will be returned during the write.
//
// Defaults to os.TempDir().
func WithTempDir(dir string) Option {
return func(w *Writer) {
if dir != "" {
w.tempDir = dir
}
}
}

mode := options.Mode
if mode == 0 {
mode = os.FileMode(0200)
// WithTempExtension sets the extension used to demarcate the temporary files
// created during a write from other normal files. The extension is appended to
// the end of the destination file name; any leading dots are stripped.
//
// Defaults to "tmp".
func WithTempExtension(ext string) Option {
ext = strings.TrimLeft(ext, ".")
return func(w *Writer) {
if ext != "" {
w.tempExt = ext
}
}
}

fileSystem := options.FS
if fileSystem == nil {
fileSystem = fs.New()
// WithMode sets the file mode of the destination file to be written.
//
// Defaults to 0660 (read-write for the owner and group).
func WithMode(mode os.FileMode) Option {
return func(w *Writer) {
if mode != 0 {
w.mode = mode
}
}
}

systemCalls := options.Sys
if systemCalls == nil {
systemCalls = sys.New()
// New creates a Writer configured with the given options. The options are
// applied in order; later options override earlier ones.
func New(options ...Option) *Writer {
w := &Writer{
tempDir: os.TempDir(),
tempExt: "tmp",
mode: os.FileMode(0660),
}

return &writer{
tmpDir: tmpDir,
tmpExt: tmpExt,
fileMode: mode,
fs: fileSystem,
sys: systemCalls,
for _, option := range options {
option(w)
}
return w
}

type writer struct {
tmpDir string
tmpExt string
fileMode os.FileMode
fs fs.FileSystem
sys sys.Syscall
}

func (w *writer) WriteFile(filePath string, source io.Reader) error {
// WriteFile writes the contents of source into a file at filePath, atomically.
func (w *Writer) WriteFile(filePath string, source io.Reader) error {
fileDir := filepath.Dir(filePath)
fileName := filepath.Base(filePath)

Expand All @@ -128,31 +100,32 @@ func (w *writer) WriteFile(filePath string, source io.Reader) error {
// a complete flush (fsync)
tmpPath, err := w.writeTmp(source, fileName)
if err != nil {
_ = w.fs.Remove(tmpPath)
if tmpPath != "" {
_ = os.Remove(tmpPath)
}
return err
}

// 3) since we know the tmp file and destination file exist on the
// same device, a filesystem rename will be an atomic operation
if err := w.rename(tmpPath, filePath); err != nil {
_ = w.fs.Remove(tmpPath)
_ = os.Remove(tmpPath)
return err
}

return nil
}

func (w *writer) checkDevice(fileDir string) error {
var stat syscall.Stat_t
if err := w.sys.Stat(fileDir, &stat); err != nil {
func (w *Writer) checkDevice(fileDir string) error {
fileDirDeviceID, err := deviceID(fileDir)
if err != nil {
return fmt.Errorf("atomicfs: unable to stat destination directory %s: %w", fileDir, err)
}
fileDirDeviceID := stat.Dev

if err := w.sys.Stat(w.tmpDir, &stat); err != nil {
return fmt.Errorf("atomicfs: unable to stat tmp directory %s: %w", w.tmpDir, err)
tmpDirDeviceID, err := deviceID(w.tempDir)
if err != nil {
return fmt.Errorf("atomicfs: unable to stat tmp directory %s: %w", w.tempDir, err)
}
tmpDirDeviceID := stat.Dev

if fileDirDeviceID != tmpDirDeviceID {
return errors.New("atomicfs: tmp & destination directories not on same device")
Expand All @@ -161,16 +134,16 @@ func (w *writer) checkDevice(fileDir string) error {
return nil
}

func (w *writer) rename(previous, next string) error {
if err := w.fs.Rename(previous, next); err != nil {
func (w *Writer) rename(previous, next string) error {
if err := os.Rename(previous, next); err != nil {
return fmt.Errorf("atomicfs: unable to rename tmp file %s to %s: %w", previous, next, err)
}
return w.syncDir(next)
}

func (w *writer) syncDir(name string) error {
func (w *Writer) syncDir(name string) error {
directory := filepath.Dir(name)
f, err := w.fs.Open(directory)
f, err := os.Open(directory)
if err != nil {
return fmt.Errorf("atomicfs: unable to open directory %s for syncing: %w", directory, err)
}
Expand All @@ -186,32 +159,32 @@ func (w *writer) syncDir(name string) error {
return nil
}

func (w *writer) writeTmp(source io.Reader, name string) (string, error) {
tmpName := fmt.Sprintf("%s.%s", name, w.tmpExt)
func (w *Writer) writeTmp(source io.Reader, name string) (string, error) {
tmpName := name + "." + w.tempExt

f, err := os.CreateTemp(w.tmpDir, tmpName)
f, err := os.CreateTemp(w.tempDir, tmpName)
if err != nil {
return "", fmt.Errorf("atomicfs: unable to create tmp file in %s: %w", w.tmpDir, err)
return "", fmt.Errorf("atomicfs: unable to create tmp file in %s: %w", w.tempDir, err)
}
tmpPath := f.Name()

if err := f.Chmod(w.fileMode); err != nil {
if err := f.Chmod(w.mode); err != nil {
_ = f.Close()
return tmpPath, fmt.Errorf("atomicfs: unable to chmod tmp file in %s: %w", w.tmpDir, err)
return tmpPath, fmt.Errorf("atomicfs: unable to chmod tmp file in %s: %w", w.tempDir, err)
}

if _, err := io.Copy(f, source); err != nil {
_ = f.Close()
return tmpPath, fmt.Errorf("atomicfs: unable to copy source into tmp file in %s: %w", w.tmpDir, err)
return tmpPath, fmt.Errorf("atomicfs: unable to copy source into tmp file in %s: %w", w.tempDir, err)
}

if err := f.Sync(); err != nil {
_ = f.Close()
return tmpPath, fmt.Errorf("atomicfs: unable to fsync tmp file in %s: %w", w.tmpDir, err)
return tmpPath, fmt.Errorf("atomicfs: unable to fsync tmp file in %s: %w", w.tempDir, err)
}

if err := f.Close(); err != nil {
return tmpPath, fmt.Errorf("atomicfs: unable to close tmp file in %s: %w", w.tmpDir, err)
return tmpPath, fmt.Errorf("atomicfs: unable to close tmp file in %s: %w", w.tempDir, err)
}

return tmpPath, nil
Expand Down
Loading