blob: f266e0102c201b0f863b999ca81a815f4e73da59 (
plain)
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
|
// SPDX-License-Identifier: GPL-3.0-or-later
package filelock
import (
"path/filepath"
"github.com/gofrs/flock"
)
func New(dir string) *Locker {
return &Locker{
suffix: ".collector.lock",
dir: dir,
locks: make(map[string]*flock.Flock),
}
}
type Locker struct {
suffix string
dir string
locks map[string]*flock.Flock
}
func (l *Locker) Lock(name string) (bool, error) {
filename := l.filename(name)
if _, ok := l.locks[filename]; ok {
return true, nil
}
locker := flock.New(filename)
ok, err := locker.TryLock()
if ok {
l.locks[filename] = locker
} else {
_ = locker.Close()
}
return ok, err
}
func (l *Locker) Unlock(name string) {
filename := l.filename(name)
locker, ok := l.locks[filename]
if !ok {
return
}
delete(l.locks, filename)
_ = locker.Close()
}
func (l *Locker) isLocked(name string) bool {
_, ok := l.locks[l.filename(name)]
return ok
}
func (l *Locker) filename(name string) string {
return filepath.Join(l.dir, name+l.suffix)
}
|