-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocking.go
64 lines (54 loc) · 1.37 KB
/
locking.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
package goserver
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
lpb "github.com/brotherlogic/lock/proto"
)
var election = promauto.NewGauge(prometheus.GaugeOpts{
Name: "server_election",
Help: "The number of active election waits",
})
func (s *GoServer) RunLockingElection(ctx context.Context, key string, detail string) (string, error) {
if s.SkipElect {
return "blah", nil
}
conn, err := s.FDialServer(ctx, "lock")
if err != nil {
return "", err
}
defer conn.Close()
client := lpb.NewLockServiceClient(conn)
// Default to a 60 second deadline
duration := time.Second * 60
dead, ok := ctx.Deadline()
if ok {
duration = time.Until(dead)
}
res, err := client.AcquireLock(ctx, &lpb.AcquireLockRequest{
Key: key,
LockDurationInSeconds: int64(duration.Seconds()),
Purpose: detail,
})
if err != nil {
return "", err
}
return res.GetLock().GetLockKey(), nil
}
func (s *GoServer) ReleaseLockingElection(ctx context.Context, key string, lockKey string) error {
if s.SkipElect {
return nil
}
conn, err := s.FDialServer(ctx, "lock")
if err != nil {
return err
}
defer conn.Close()
client := lpb.NewLockServiceClient(conn)
_, err = client.ReleaseLock(ctx, &lpb.ReleaseLockRequest{
Key: key,
LockKey: lockKey,
})
return err
}