2024-05-24 14:57:16 +00:00
|
|
|
package etcd
|
|
|
|
|
|
|
|
import (
|
2024-05-24 15:51:49 +00:00
|
|
|
"context"
|
2024-05-24 14:57:16 +00:00
|
|
|
"errors"
|
2024-05-24 15:51:49 +00:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
2024-05-24 14:57:16 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/RichardKnop/machinery/v2/config"
|
|
|
|
"github.com/RichardKnop/machinery/v2/locks/iface"
|
|
|
|
"github.com/RichardKnop/machinery/v2/log"
|
|
|
|
clientv3 "go.etcd.io/etcd/client/v3"
|
2024-05-24 15:51:49 +00:00
|
|
|
"go.etcd.io/etcd/client/v3/concurrency"
|
2024-05-24 14:57:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrRedisLockFailed = errors.New("redis lock: failed to acquire lock")
|
|
|
|
)
|
|
|
|
|
|
|
|
type etcdLock struct {
|
|
|
|
globalConf *config.Config
|
|
|
|
conf clientv3.Config
|
|
|
|
cli *clientv3.Client
|
|
|
|
retries int
|
|
|
|
}
|
|
|
|
|
2024-05-24 15:51:49 +00:00
|
|
|
func New(cnf *config.Config, endpoint string, retries int) (iface.Lock, error) {
|
2024-05-24 14:57:16 +00:00
|
|
|
etcdConf := clientv3.Config{Endpoints: []string{endpoint}}
|
|
|
|
cli, err := clientv3.New(etcdConf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
lock := etcdLock{
|
|
|
|
globalConf: cnf,
|
|
|
|
conf: etcdConf,
|
|
|
|
cli: cli,
|
2024-05-24 15:51:49 +00:00
|
|
|
retries: retries,
|
2024-05-24 14:57:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return &lock, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r etcdLock) LockWithRetries(key string, unixTsToExpireNs int64) error {
|
2024-05-24 15:51:49 +00:00
|
|
|
for i := 0; i < r.retries; i++ {
|
|
|
|
err := r.Lock(key, unixTsToExpireNs)
|
|
|
|
if err == nil {
|
|
|
|
// 成功拿到锁,返回
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
log.INFO.Printf("acquired lock=%s failed, retries=%d", key, i)
|
|
|
|
time.Sleep(time.Millisecond * 100)
|
|
|
|
}
|
|
|
|
return ErrRedisLockFailed
|
|
|
|
|
2024-05-24 14:57:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r etcdLock) Lock(key string, unixTsToExpireNs int64) error {
|
2024-05-24 15:51:49 +00:00
|
|
|
now := time.Now().UnixNano()
|
|
|
|
ttl := time.Duration(unixTsToExpireNs + 1 - now)
|
|
|
|
lease := clientv3.NewLease(r.cli)
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
resp, err := lease.Grant(ctx, int64(ttl.Seconds()))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// 创建一个新的session
|
|
|
|
s, err := concurrency.NewSession(r.cli, concurrency.WithLease(resp.ID))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
key = fmt.Sprintf("/machinery/v2/lock/%s", strings.TrimRight(key, "/"))
|
|
|
|
m := concurrency.NewMutex(s, key)
|
|
|
|
|
|
|
|
if err := m.Lock(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.INFO.Printf("acquired lock=%s, duration=%s", key, ttl)
|
|
|
|
return nil
|
2024-05-24 14:57:16 +00:00
|
|
|
}
|