-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfslock.go
86 lines (74 loc) · 1.93 KB
/
fslock.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
package fslock
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
util "github.com/ipfs/go-ipfs-util"
logging "github.com/ipfs/go-log/v2"
lock "go4.org/lock"
)
// log is the fsrepo logger
var log = logging.Logger("lock")
// LockedError is returned as the inner error type when the lock is already
// taken.
type LockedError string
func (e LockedError) Error() string {
return string(e)
}
// Lock creates the lock.
func Lock(confdir, lockFileName string) (io.Closer, error) {
lockFilePath := filepath.Join(confdir, lockFileName)
lk, err := lock.Lock(lockFilePath)
if err != nil {
switch {
case lockedByOthers(err):
return lk, &os.PathError{
Op: "lock",
Path: lockFilePath,
Err: LockedError("someone else has the lock"),
}
case strings.Contains(err.Error(), "already locked"):
// we hold the lock ourselves
return lk, &os.PathError{
Op: "lock",
Path: lockFilePath,
Err: LockedError("lock is already held by us"),
}
case os.IsPermission(err) || isLockCreatePermFail(err):
// lock fails on permissions error
// Using a path error like this ensures that
// os.IsPermission works on the returned error.
return lk, &os.PathError{
Op: "lock",
Path: lockFilePath,
Err: os.ErrPermission,
}
}
}
return lk, err
}
// Locked checks if there is a lock already set.
func Locked(confdir, lockFile string) (bool, error) {
log.Debugf("Checking lock")
if !util.FileExists(filepath.Join(confdir, lockFile)) {
log.Debugf("File doesn't exist: %s", filepath.Join(confdir, lockFile))
return false, nil
}
lk, err := Lock(confdir, lockFile)
if err == nil {
log.Debugf("No one has a lock")
lk.Close()
return false, nil
}
log.Debug(err)
if errors.As(err, new(LockedError)) {
return true, nil
}
return false, err
}
func isLockCreatePermFail(err error) bool {
s := err.Error()
return strings.Contains(s, "Lock Create of") && strings.Contains(s, "permission denied")
}