~james/core

core/spindle/instance_lock_unix.go -rw-r--r-- 745 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//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
}