forked from monochromegane/gannoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.go
89 lines (72 loc) · 1.93 KB
/
lock.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package gannoy
import (
"io"
"os/exec"
"strings"
"syscall"
"github.com/coreos/go-semver/semver"
"regexp"
)
type Locker interface {
ReadLock(uintptr, int64, int64) error
WriteLock(uintptr, int64, int64) error
UnLock(uintptr, int64, int64) error
}
func newLocker() Locker {
bytes, err := exec.Command("uname", "-sr").Output()
if err != nil {
return Flock{}
}
if validateKernel(bytes) {
return Fcntl{}
}
return Flock{}
}
func validateKernel(bytes []byte) bool {
kernel := strings.Split(strings.TrimRight(string(bytes), "\n"), " ")
nk := normalizeKernelVersion(kernel[1])
if kernel[0] == "Linux" && !semver.New(nk).LessThan(*semver.New("3.15.0")) {
return true
}
return false
}
func normalizeKernelVersion(v string) string {
re := regexp.MustCompile(".elrepo.x86_64|.el7.x86_64")
return re.ReplaceAllString(v, "")
}
// Only Linux and kernel version 3.15 or later.
// This depends on open file description lock (F_OFD_SETLKW).
type Fcntl struct {
}
const F_OFD_SETLKW = 38
func (f Fcntl) ReadLock(fd uintptr, start, len int64) error {
return f.fcntl(syscall.F_RDLCK, fd, start, len)
}
func (f Fcntl) WriteLock(fd uintptr, start, len int64) error {
return f.fcntl(syscall.F_WRLCK, fd, start, len)
}
func (f Fcntl) UnLock(fd uintptr, start, len int64) error {
return f.fcntl(syscall.F_UNLCK, fd, start, len)
}
func (f Fcntl) fcntl(typ int16, fd uintptr, start, len int64) error {
return syscall.FcntlFlock(fd, F_OFD_SETLKW, &syscall.Flock_t{
Start: start,
Len: len,
Type: typ,
Whence: io.SeekStart,
})
}
type Flock struct {
}
func (f Flock) ReadLock(fd uintptr, start, len int64) error {
return f.flock(fd, syscall.LOCK_SH)
}
func (f Flock) WriteLock(fd uintptr, start, len int64) error {
return f.flock(fd, syscall.LOCK_EX)
}
func (f Flock) UnLock(fd uintptr, start, len int64) error {
return f.flock(fd, syscall.LOCK_UN)
}
func (f Flock) flock(fd uintptr, how int) error {
return syscall.Flock(int(fd), how)
}