2018-11-10 23:33:06 +00:00
|
|
|
// Package etcd3locker provides a locking mechanism using an etcd3 cluster.
|
|
|
|
// Tested on etcd 3.1/3.2./3.3
|
2018-11-10 20:05:44 +00:00
|
|
|
package etcd3locker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
2019-06-16 15:06:17 +00:00
|
|
|
"github.com/coreos/etcd/clientv3/concurrency"
|
2019-09-11 10:03:39 +00:00
|
|
|
"github.com/tus/tusd/pkg/handler"
|
2018-11-10 20:05:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type etcd3Lock struct {
|
|
|
|
Id string
|
|
|
|
Mutex *concurrency.Mutex
|
|
|
|
Session *concurrency.Session
|
2019-09-11 10:03:39 +00:00
|
|
|
|
|
|
|
isHeld bool
|
2018-11-10 20:05:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func newEtcd3Lock(session *concurrency.Session, id string) *etcd3Lock {
|
|
|
|
return &etcd3Lock{
|
|
|
|
Mutex: concurrency.NewMutex(session, id),
|
|
|
|
Session: session,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-10 23:33:06 +00:00
|
|
|
// Acquires a lock from etcd3
|
2019-09-11 10:03:39 +00:00
|
|
|
func (lock *etcd3Lock) Lock() error {
|
|
|
|
if lock.isHeld {
|
|
|
|
return handler.ErrFileLocked
|
|
|
|
}
|
|
|
|
|
2018-11-10 20:05:44 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// this is a blocking call; if we receive DeadlineExceeded
|
|
|
|
// the lock is most likely already taken
|
|
|
|
if err := lock.Mutex.Lock(ctx); err != nil {
|
|
|
|
if err == context.DeadlineExceeded {
|
2019-06-11 16:23:20 +00:00
|
|
|
return handler.ErrFileLocked
|
2018-11-10 20:05:44 +00:00
|
|
|
} else {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2019-09-11 10:03:39 +00:00
|
|
|
|
|
|
|
lock.isHeld = true
|
2018-11-10 20:05:44 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-11-10 23:33:06 +00:00
|
|
|
// Releases a lock from etcd3
|
2019-09-11 10:03:39 +00:00
|
|
|
func (lock *etcd3Lock) Unlock() error {
|
|
|
|
if !lock.isHeld {
|
|
|
|
return ErrLockNotHeld
|
|
|
|
}
|
2018-11-10 20:05:44 +00:00
|
|
|
|
2019-09-11 10:03:39 +00:00
|
|
|
lock.isHeld = false
|
|
|
|
defer lock.Session.Close()
|
|
|
|
return lock.Mutex.Unlock(context.Background())
|
2018-11-10 20:05:44 +00:00
|
|
|
}
|