-
Notifications
You must be signed in to change notification settings - Fork 6
/
lock.go
85 lines (64 loc) · 1.98 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
//go:build !windows
// +build !windows
// Package lock provides methods for working with lock files
package lock
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2024 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"os"
"time"
"github.com/essentialkaos/ek/v12/fsutil"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// Create creates new lock file
func Create(name string) error {
err := fsutil.ValidatePerms("DW", Dir)
if err != nil {
return err
}
return fsutil.TouchFile(getLockPath(name), 0644)
}
// Remove deletes lock file
func Remove(name string) error {
err := fsutil.ValidatePerms("DW", Dir)
if err != nil {
return err
}
return os.Remove(getLockPath(name))
}
// Has returns true if lock file exists
func Has(name string) bool {
return fsutil.IsExist(getLockPath(name))
}
// Wait waits until lock file being deleted
func Wait(name string, deadline time.Time) bool {
if !Has(name) {
return true
}
for range time.NewTicker(time.Second / 4).C {
if !deadline.IsZero() && time.Now().After(deadline) {
return false
}
if !Has(name) {
break
}
}
return true
}
// IsExpired returns true if lock file reached TTL
func IsExpired(name string, ttl time.Duration) bool {
ct, err := fsutil.GetCTime(getLockPath(name))
if err != nil {
return false
}
return time.Since(ct) > ttl
}
// ////////////////////////////////////////////////////////////////////////////////// //
// getLockPath returns path to lock file
func getLockPath(name string) string {
return Dir + "/" + name + ".lock"
}