forked from mutagen-io/mutagen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
49 lines (41 loc) · 1.26 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
package daemon
import (
"github.com/pkg/errors"
"github.com/havoc-io/mutagen/pkg/filesystem"
)
const (
// lockName is the name of the daemon lock file. It resides within the
// daemon subdirectory of the Mutagen directory.
lockName = "daemon.lock"
)
// Lock represents a daemon lock instance.
type Lock struct {
// locker is the daemon file lock, uniquely held by a single daemon
// instance. Because the locking semantics vary by platform, hosting
// processes should only attempt to create a single daemon lock at a time.
locker *filesystem.Locker
}
// AcquireLock attempts to acquire the daemon lock. It is the only way to
// acquire a Lock instance.
func AcquireLock() (*Lock, error) {
// Compute the lock path.
lockPath, err := subpath(lockName)
if err != nil {
return nil, errors.Wrap(err, "unable to compute daemon lock path")
}
// Create the daemon locker and attempt to acquire the lock.
locker, err := filesystem.NewLocker(lockPath, 0600)
if err != nil {
return nil, errors.Wrap(err, "unable to create daemon locker")
} else if err = locker.Lock(false); err != nil {
return nil, err
}
// Create the lock.
return &Lock{
locker: locker,
}, nil
}
// Unlock releases the daemon lock.
func (l *Lock) Unlock() error {
return l.locker.Unlock()
}