mirror of
https://github.com/hanzoai/cloud.git
synced 2026-11-17 16:36:24 +00:00
33 lines
903 B
Go
33 lines
903 B
Go
//go:build !windows
|
|
|
|
package cek
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"syscall"
|
|
)
|
|
|
|
// flock takes an exclusive advisory lock on <path>.cek.lock, serializing
|
|
// first-touch and migration for the SAME database across processes/goroutines
|
|
// (different databases never contend). Returns an unlock func.
|
|
func flock(path string) (func(), error) {
|
|
lockPath := path + lockSuffix
|
|
if err := os.MkdirAll(filepath.Dir(lockPath), 0o700); err != nil {
|
|
return nil, fmt.Errorf("cek: create lock dir: %w", err)
|
|
}
|
|
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o600)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cek: open lock %q: %w", lockPath, err)
|
|
}
|
|
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
|
|
_ = f.Close()
|
|
return nil, fmt.Errorf("cek: acquire lock %q: %w", lockPath, err)
|
|
}
|
|
return func() {
|
|
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
|
|
_ = f.Close()
|
|
}, nil
|
|
}
|