-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathlock.go
138 lines (114 loc) · 2.32 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
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
137
138
package dbcore
import (
"context"
"os"
"strings"
"time"
log "github.com/win5do/go-lib/logx"
"gorm.io/gorm"
"github.com/win5do/go-lib/errx"
)
const DefaultLeaseAge = 60 * time.Second
type lock struct {
CommonModel
ExpiredAt time.Time
Action string `gorm:"unique;not null"`
Holder string
}
func init() {
RegisterInjector(func(d *gorm.DB) {
SetupTableModel(d, &lock{})
})
}
type lockDb struct {
db *gorm.DB
stopCh chan struct{}
action string
holder string
leaseAge time.Duration
}
func NewLockDb(action, holder string, lease time.Duration) *lockDb {
return &lockDb{
db: GetDB(context.Background()),
stopCh: make(chan struct{}),
action: action,
holder: holder,
leaseAge: lease,
}
}
func (s *lockDb) Lock() (bool, error) {
err := s.cleanExpired()
if err != nil {
return false, errx.WithStackOnce(err)
}
err = s.db.Create(&lock{
ExpiredAt: time.Now().Add(s.leaseAge),
Action: s.action,
Holder: s.holder,
}).Error
if err != nil {
// Duplicate entry '<action_val>' for key 'action'
if strings.Contains(err.Error(), "Duplicate entry") {
return false, nil
}
return false, errx.WithStackOnce(err)
}
s.startLease()
log.Debugf("%s get lock", s.holder)
return true, nil
}
func (s *lockDb) UnLock() error {
s.stopLease()
var err error
defer func() {
err = s.db.
Where("action = ? and holder = ?", s.action, s.holder).
Delete(&lock{}).
Error
}()
return err
}
func (s *lockDb) cleanExpired() error {
err := s.db.
Where("expired_at < ?", time.Now()).
Delete(&lock{}).
Error
return err
}
func (s *lockDb) startLease() {
go func() {
// 剩余 1/4 时刷新租约
ticker := time.NewTicker(s.leaseAge * 3 / 4)
for {
select {
case <-ticker.C:
err := s.refreshLease()
if err != nil {
log.Errorf("refreash lease err: %s", err)
} else {
log.Debug("lease refreshed")
}
case <-s.stopCh:
log.Debug("lease stopped")
return
}
}
}()
}
func (s *lockDb) stopLease() {
close(s.stopCh)
}
func (s *lockDb) refreshLease() error {
err := s.db.Model(&lock{}).
Where("action = ? and holder = ?", s.action, s.holder).
Update("expired_at", time.Now().Add(s.leaseAge)).
Error
return err
}
func GetHostname() string {
host, err := os.Hostname()
if err != nil {
log.Fatal("err: %+v", err)
}
return host
}