| 1 |
// Copyright (c) 2014-2019 Ludovic Fauvet |
| 2 |
// Licensed under the MIT license |
| 3 |
|
| 4 |
package network |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"os" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/etix/mirrorbits/database" |
| 12 |
"github.com/gomodule/redigo/redis" |
| 13 |
) |
| 14 |
|
| 15 |
const ( |
| 16 |
lockTTL = 10 // in seconds |
| 17 |
lockRefresh = 5 // in seconds |
| 18 |
) |
| 19 |
|
| 20 |
// ClusterLock holds the internal structure of a ClusterLock |
| 21 |
type ClusterLock struct { |
| 22 |
redis *database.Redis |
| 23 |
key string |
| 24 |
identifier string |
| 25 |
done chan struct{} |
| 26 |
} |
| 27 |
|
| 28 |
// NewClusterLock returns a new instance of a ClusterLock. |
| 29 |
// A ClucterLock is used to maitain a lock on a mirror that is being |
| 30 |
// scanned. The lock is renewed every lockRefresh seconds and is |
| 31 |
// automatically released by the redis database every lockTTL seconds |
| 32 |
// allowing the lock to be released even if the application is killed. |
| 33 |
func NewClusterLock(redis *database.Redis, key, identifier string) *ClusterLock { |
| 34 |
return &ClusterLock{ |
| 35 |
redis: redis, |
| 36 |
key: key, |
| 37 |
identifier: identifier, |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
// Get tries to obtain an exclusive lock, cluster wide, for the given mirror |
| 42 |
func (n *ClusterLock) Get() (<-chan struct{}, error) { |
| 43 |
if n.done != nil { |
| 44 |
return nil, errors.New("lock already in use") |
| 45 |
} |
| 46 |
|
| 47 |
conn := n.redis.Get() |
| 48 |
defer conn.Close() |
| 49 |
|
| 50 |
if conn.Err() != nil { |
| 51 |
return nil, conn.Err() |
| 52 |
} |
| 53 |
|
| 54 |
_, err := redis.String(conn.Do("SET", n.key, 1, "NX", "EX", lockTTL)) |
| 55 |
if err == redis.ErrNil { |
| 56 |
return nil, nil |
| 57 |
} else if err != nil { |
| 58 |
return nil, err |
| 59 |
} |
| 60 |
|
| 61 |
n.done = make(chan struct{}) |
| 62 |
|
| 63 |
// Maintain the lock active until release |
| 64 |
go func() { |
| 65 |
conn := n.redis.Get() |
| 66 |
defer conn.Close() |
| 67 |
|
| 68 |
for { |
| 69 |
select { |
| 70 |
case <-n.done: |
| 71 |
n.done = nil |
| 72 |
conn.Do("DEL", n.key) |
| 73 |
return |
| 74 |
case <-time.After(lockRefresh * time.Second): |
| 75 |
result, err := redis.Int(conn.Do("EXPIRE", n.key, lockTTL)) |
| 76 |
if err != nil { |
| 77 |
log.Errorf("Renewing lock for %s failed: %s", n.identifier, err) |
| 78 |
return |
| 79 |
} else if result == 0 { |
| 80 |
log.Errorf("Renewing lock for %s failed: lock disappeared", n.identifier) |
| 81 |
return |
| 82 |
} |
| 83 |
if os.Getenv("DEBUG") != "" { |
| 84 |
log.Debugf("[%s] Lock renewed", n.identifier) |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
}() |
| 89 |
|
| 90 |
return n.done, nil |
| 91 |
} |
| 92 |
|
| 93 |
// Release releases the exclusive lock on the mirror |
| 94 |
func (n *ClusterLock) Release() { |
| 95 |
close(n.done) |
| 96 |
} |