//go:build unix
package spindle
import (
"errors"
"fmt"
"os"
"syscall"
)
// two spindles on one db would orphan workflows and double run pulls
func lockInstance(dbPath string) (release func(), err error) {
if dbPath == "" {
return func() {}, nil
}
file, err := os.OpenFile(dbPath+".lock", os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, fmt.Errorf("opening the instance lock: %w", err)
}
if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
_ = file.Close()
if errors.Is(err, syscall.EWOULDBLOCK) {
return nil, fmt.Errorf("another spindle is running on %s", dbPath)
}
return nil, fmt.Errorf("locking %s.lock: %w", dbPath, err)
}
return func() { _ = file.Close() }, nil
}