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-11 16:23:20 +00:00
|
|
|
"github.com/tus/tusd/pkg/handler"
|
2019-06-16 15:06:17 +00:00
|
|
|
"github.com/coreos/etcd/clientv3/concurrency"
|
2018-11-10 20:05:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type etcd3Lock struct {
|
|
|
|
Id string
|
|
|
|
Mutex *concurrency.Mutex
|
|
|
|
Session *concurrency.Session
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2018-11-10 20:05:44 +00:00
|
|
|
func (lock *etcd3Lock) Acquire() error {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-11-10 23:33:06 +00:00
|
|
|
// Releases a lock from etcd3
|
2018-11-10 20:05:44 +00:00
|
|
|
func (lock *etcd3Lock) Release() error {
|
|
|
|
return lock.Mutex.Unlock(context.Background())
|
|
|
|
}
|
|
|
|
|
2018-11-10 23:33:06 +00:00
|
|
|
// Closes etcd3 session
|
2018-11-10 20:05:44 +00:00
|
|
|
func (lock *etcd3Lock) CloseSession() error {
|
|
|
|
return lock.Session.Close()
|
|
|
|
}
|