-
Notifications
You must be signed in to change notification settings - Fork 12
/
flock.go
136 lines (106 loc) · 2.03 KB
/
flock.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package util
import (
"os"
"sync"
"syscall"
"github.com/projecteru2/yavirt/errors"
"github.com/projecteru2/yavirt/log"
)
const perm = os.FileMode(0600)
// Flock .
type Flock struct {
mut sync.Mutex
fpth string
file *os.File
locked bool
}
// NewFlock .
func NewFlock(fpth string) *Flock {
return &Flock{fpth: fpth}
}
// Trylock .
func (f *Flock) Trylock() error {
f.mut.Lock()
defer f.mut.Unlock()
if f.locked {
return nil
}
if err := f.open(); err != nil {
return errors.Trace(err)
}
return f.flock(true)
}
func (f *Flock) flock(retry bool) error {
switch err := syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); {
case err == nil:
f.locked = true
return nil
case err == syscall.EWOULDBLOCK:
fallthrough
case err != syscall.EIO && err != syscall.EBADF:
fallthrough
case !retry:
return errors.Errorf("%s has locked yet", f.fpth)
}
var stat, err = f.file.Stat()
if err != nil {
return errors.Trace(err)
}
if stat.Mode()&0600 == 0600 { //nolint
if err := f.reopen(); err != nil {
return errors.Trace(err)
}
}
return f.flock(false)
}
func (f *Flock) reopen() error {
f.close()
return f.open()
}
func (f *Flock) open() error {
if f.file != nil {
return nil
}
var fh, err = os.OpenFile(f.fpth, os.O_CREATE|os.O_RDWR, perm)
if err != nil {
return errors.Trace(err)
}
f.file = fh
return nil
}
// Close .
func (f *Flock) Close() {
f.mut.Lock()
defer f.mut.Unlock()
if !f.locked {
return
}
if err := f.unlock(); err != nil {
log.WarnStack(err)
}
if err := os.Remove(f.fpth); err != nil {
log.WarnStack(err)
}
}
// Unlock .
func (f *Flock) Unlock() {
f.mut.Lock()
defer f.mut.Unlock()
if err := f.unlock(); err != nil {
log.WarnStack(err)
}
}
func (f *Flock) unlock() error {
if err := syscall.Flock(int(f.file.Fd()), syscall.LOCK_UN); err != nil {
return errors.Trace(err)
}
f.locked = false
f.close()
return nil
}
func (f *Flock) close() {
if err := f.file.Close(); err != nil {
log.Warnf("[util] close %s failed", f.fpth)
}
f.file = nil
}