2015-05-24 16:38:49 +00:00
|
|
|
package physical
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2016-01-27 22:15:52 +00:00
|
|
|
"fmt"
|
2016-04-26 03:10:32 +00:00
|
|
|
"log"
|
2015-11-16 22:30:02 +00:00
|
|
|
"net/url"
|
2015-12-17 11:48:13 +00:00
|
|
|
"os"
|
2015-05-24 16:38:49 +00:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
2015-05-31 19:02:11 +00:00
|
|
|
"sync"
|
2015-05-24 16:38:49 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/armon/go-metrics"
|
2015-11-16 06:12:06 +00:00
|
|
|
"github.com/coreos/etcd/client"
|
|
|
|
"github.com/coreos/etcd/pkg/transport"
|
|
|
|
"golang.org/x/net/context"
|
2015-05-24 16:38:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// Ideally, this prefix would match the "_" used in the file backend, but
|
|
|
|
// that prefix has special meaining in etcd. Specifically, it excludes those
|
|
|
|
// entries from directory listings.
|
|
|
|
EtcdNodeFilePrefix = "."
|
|
|
|
|
2015-05-31 19:02:11 +00:00
|
|
|
// The lock prefix can (and probably should) cause an entry to be excluded
|
|
|
|
// from diretory listings, so "_" works here.
|
|
|
|
EtcdNodeLockPrefix = "_"
|
|
|
|
|
2015-05-24 16:38:49 +00:00
|
|
|
// The delimiter is the same as the `-C` flag of etcdctl.
|
|
|
|
EtcdMachineDelimiter = ","
|
2015-05-31 19:02:11 +00:00
|
|
|
|
|
|
|
// The lock TTL matches the default that Consul API uses, 15 seconds.
|
2015-11-16 06:12:06 +00:00
|
|
|
EtcdLockTTL = 15 * time.Second
|
2015-06-02 15:03:17 +00:00
|
|
|
|
2015-09-09 16:33:07 +00:00
|
|
|
// The amount of time to wait between the semaphore key renewals
|
|
|
|
EtcdLockRenewInterval = 5 * time.Second
|
|
|
|
|
2015-06-02 15:03:17 +00:00
|
|
|
// The ammount of time to wait if a watch fails before trying again.
|
|
|
|
EtcdWatchRetryInterval = time.Second
|
|
|
|
|
|
|
|
// The number of times to re-try a failed watch before signaling that leadership is lost.
|
|
|
|
EtcdWatchRetryMax = 5
|
2015-05-24 16:38:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2016-01-11 18:56:58 +00:00
|
|
|
EtcdSyncConfigError = errors.New("client setup failed: unable to parse etcd sync field in config")
|
2015-05-31 19:02:11 +00:00
|
|
|
EtcdSyncClusterError = errors.New("client setup failed: unable to sync etcd cluster")
|
2015-11-16 22:30:02 +00:00
|
|
|
EtcdAddressError = errors.New("client setup failed: address must be valid URL (ex. 'scheme://host:port')")
|
2015-05-31 19:02:11 +00:00
|
|
|
EtcdSemaphoreKeysEmptyError = errors.New("lock queue is empty")
|
|
|
|
EtcdLockHeldError = errors.New("lock already held")
|
|
|
|
EtcdLockNotHeldError = errors.New("lock not held")
|
|
|
|
EtcdSemaphoreKeyRemovedError = errors.New("semaphore key removed before lock aquisition")
|
2015-05-24 16:38:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// errorIsMissingKey returns true if the given error is an etcd error with an
|
|
|
|
// error code corresponding to a missing key.
|
|
|
|
func errorIsMissingKey(err error) bool {
|
2015-12-07 07:29:20 +00:00
|
|
|
etcdErr, ok := err.(client.Error)
|
|
|
|
return ok && etcdErr.Code == client.ErrorCodeKeyNotFound
|
2015-05-24 16:38:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// EtcdBackend is a physical backend that stores data at specific
|
|
|
|
// prefix within Etcd. It is used for most production situations as
|
|
|
|
// it allows Vault to run on multiple machines in a highly-available manner.
|
|
|
|
type EtcdBackend struct {
|
2015-11-16 06:38:21 +00:00
|
|
|
path string
|
|
|
|
kAPI client.KeysAPI
|
|
|
|
permitPool *PermitPool
|
2016-04-26 03:10:32 +00:00
|
|
|
logger *log.Logger
|
2015-05-24 16:38:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// newEtcdBackend constructs a etcd backend using a given machine address.
|
2016-04-26 03:10:32 +00:00
|
|
|
func newEtcdBackend(conf map[string]string, logger *log.Logger) (Backend, error) {
|
2015-05-24 16:38:49 +00:00
|
|
|
// Get the etcd path form the configuration.
|
|
|
|
path, ok := conf["path"]
|
|
|
|
if !ok {
|
|
|
|
path = "/vault"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure path is prefixed.
|
|
|
|
if !strings.HasPrefix(path, "/") {
|
|
|
|
path = "/" + path
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set a default machines list and check for an overriding address value.
|
2016-05-10 19:50:11 +00:00
|
|
|
machines := "http://127.0.0.1:2379"
|
2015-05-24 16:38:49 +00:00
|
|
|
if address, ok := conf["address"]; ok {
|
|
|
|
machines = address
|
|
|
|
}
|
2015-11-06 07:37:01 +00:00
|
|
|
machinesParsed := strings.Split(machines, EtcdMachineDelimiter)
|
|
|
|
|
2015-11-16 22:30:02 +00:00
|
|
|
// Verify that the machines are valid URLs
|
|
|
|
for _, machine := range machinesParsed {
|
2015-11-17 23:18:50 +00:00
|
|
|
u, urlErr := url.Parse(machine)
|
|
|
|
if urlErr != nil || u.Scheme == "" {
|
2015-11-16 22:30:02 +00:00
|
|
|
return nil, EtcdAddressError
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-06 08:34:20 +00:00
|
|
|
// Create a new client from the supplied address and attempt to sync with the
|
|
|
|
// cluster.
|
2015-11-16 06:12:06 +00:00
|
|
|
var cTransport client.CancelableTransport
|
|
|
|
cert, hasCert := conf["tls_cert_file"]
|
|
|
|
key, hasKey := conf["tls_key_file"]
|
|
|
|
ca, hasCa := conf["tls_ca_file"]
|
|
|
|
if (hasCert && hasKey) || hasCa {
|
|
|
|
var transportErr error
|
|
|
|
tls := transport.TLSInfo{
|
|
|
|
CAFile: ca,
|
|
|
|
CertFile: cert,
|
|
|
|
KeyFile: key,
|
|
|
|
}
|
2016-01-27 22:15:52 +00:00
|
|
|
cTransport, transportErr = transport.NewTransport(tls, 30*time.Second)
|
2015-11-16 06:12:06 +00:00
|
|
|
|
|
|
|
if transportErr != nil {
|
|
|
|
return nil, transportErr
|
2015-11-06 07:37:01 +00:00
|
|
|
}
|
|
|
|
} else {
|
2015-11-16 06:12:06 +00:00
|
|
|
cTransport = client.DefaultTransport
|
|
|
|
}
|
|
|
|
|
|
|
|
cfg := client.Config{
|
|
|
|
Endpoints: machinesParsed,
|
|
|
|
Transport: cTransport,
|
|
|
|
}
|
|
|
|
|
2015-12-17 11:48:13 +00:00
|
|
|
// Set credentials.
|
|
|
|
username := os.Getenv("ETCD_USERNAME")
|
|
|
|
if username == "" {
|
|
|
|
username, _ = conf["username"]
|
|
|
|
}
|
|
|
|
|
|
|
|
password := os.Getenv("ETCD_PASSWORD")
|
|
|
|
if password == "" {
|
|
|
|
password, _ = conf["password"]
|
|
|
|
}
|
|
|
|
|
|
|
|
if username != "" && password != "" {
|
|
|
|
cfg.Username = username
|
|
|
|
cfg.Password = password
|
|
|
|
}
|
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
c, err := client.New(cfg)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2015-11-06 07:37:01 +00:00
|
|
|
}
|
2015-11-16 06:12:06 +00:00
|
|
|
|
2016-01-11 18:56:58 +00:00
|
|
|
// Should we sync the cluster state? There are three available options
|
|
|
|
// for our client library: don't sync (required for some proxies), sync
|
|
|
|
// once, or sync periodically with AutoSync. We currently support the
|
|
|
|
// first two.
|
2016-01-27 22:15:52 +00:00
|
|
|
sync, ok := conf["sync"]
|
|
|
|
if !ok {
|
|
|
|
sync = "yes"
|
2016-01-11 18:56:58 +00:00
|
|
|
}
|
2016-01-27 22:15:52 +00:00
|
|
|
switch sync {
|
|
|
|
case "yes", "true", "y", "1":
|
2016-01-11 18:56:58 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
|
|
|
|
syncErr := c.Sync(ctx)
|
|
|
|
cancel()
|
|
|
|
if syncErr != nil {
|
2016-02-26 20:15:23 +00:00
|
|
|
return nil, fmt.Errorf("%s: %s", EtcdSyncClusterError, syncErr)
|
2016-01-11 18:56:58 +00:00
|
|
|
}
|
2016-01-27 22:15:52 +00:00
|
|
|
case "no", "false", "n", "0":
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("value of 'sync' could not be understood")
|
2015-05-24 16:38:49 +00:00
|
|
|
}
|
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
kAPI := client.NewKeysAPI(c)
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Setup the backend.
|
2015-05-24 16:38:49 +00:00
|
|
|
return &EtcdBackend{
|
2016-01-27 22:15:52 +00:00
|
|
|
path: path,
|
|
|
|
kAPI: kAPI,
|
2015-11-16 06:38:21 +00:00
|
|
|
permitPool: NewPermitPool(DefaultParallelOperations),
|
2016-04-26 03:10:32 +00:00
|
|
|
logger: logger,
|
2015-05-24 16:38:49 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put is used to insert or update an entry.
|
|
|
|
func (c *EtcdBackend) Put(entry *Entry) error {
|
|
|
|
defer metrics.MeasureSince([]string{"etcd", "put"}, time.Now())
|
|
|
|
value := base64.StdEncoding.EncodeToString(entry.Value)
|
2015-11-16 06:38:21 +00:00
|
|
|
|
|
|
|
c.permitPool.Acquire()
|
|
|
|
defer c.permitPool.Release()
|
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
_, err := c.kAPI.Set(context.Background(), c.nodePath(entry.Key), value, nil)
|
2015-05-24 16:38:49 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get is used to fetch an entry.
|
|
|
|
func (c *EtcdBackend) Get(key string) (*Entry, error) {
|
|
|
|
defer metrics.MeasureSince([]string{"etcd", "get"}, time.Now())
|
|
|
|
|
2015-11-16 06:38:21 +00:00
|
|
|
c.permitPool.Acquire()
|
|
|
|
defer c.permitPool.Release()
|
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
getOpts := &client.GetOptions{
|
|
|
|
Recursive: false,
|
2016-01-27 22:15:52 +00:00
|
|
|
Sort: false,
|
2015-11-16 06:12:06 +00:00
|
|
|
}
|
|
|
|
response, err := c.kAPI.Get(context.Background(), c.nodePath(key), getOpts)
|
2015-05-24 16:38:49 +00:00
|
|
|
if err != nil {
|
|
|
|
if errorIsMissingKey(err) {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode the stored value from base-64.
|
|
|
|
value, err := base64.StdEncoding.DecodeString(response.Node.Value)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Construct and return a new entry.
|
|
|
|
return &Entry{
|
|
|
|
Key: key,
|
|
|
|
Value: value,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete is used to permanently delete an entry.
|
|
|
|
func (c *EtcdBackend) Delete(key string) error {
|
|
|
|
defer metrics.MeasureSince([]string{"etcd", "delete"}, time.Now())
|
|
|
|
|
2015-11-16 06:38:21 +00:00
|
|
|
c.permitPool.Acquire()
|
|
|
|
defer c.permitPool.Release()
|
|
|
|
|
2015-05-24 16:38:49 +00:00
|
|
|
// Remove the key, non-recursively.
|
2015-11-16 06:12:06 +00:00
|
|
|
delOpts := &client.DeleteOptions{
|
|
|
|
Recursive: false,
|
|
|
|
}
|
|
|
|
_, err := c.kAPI.Delete(context.Background(), c.nodePath(key), delOpts)
|
2015-05-24 16:38:49 +00:00
|
|
|
if err != nil && !errorIsMissingKey(err) {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// List is used to list all the keys under a given prefix, up to the next
|
|
|
|
// prefix.
|
|
|
|
func (c *EtcdBackend) List(prefix string) ([]string, error) {
|
|
|
|
defer metrics.MeasureSince([]string{"etcd", "list"}, time.Now())
|
|
|
|
|
|
|
|
// Set a directory path from the given prefix.
|
|
|
|
path := c.nodePathDir(prefix)
|
|
|
|
|
2015-11-16 06:38:21 +00:00
|
|
|
c.permitPool.Acquire()
|
|
|
|
defer c.permitPool.Release()
|
|
|
|
|
2015-05-24 16:38:49 +00:00
|
|
|
// Get the directory, non-recursively, from etcd. If the directory is
|
|
|
|
// missing, we just return an empty list of contents.
|
2015-11-16 06:12:06 +00:00
|
|
|
getOpts := &client.GetOptions{
|
|
|
|
Recursive: false,
|
2016-01-27 22:15:52 +00:00
|
|
|
Sort: true,
|
2015-11-16 06:12:06 +00:00
|
|
|
}
|
|
|
|
response, err := c.kAPI.Get(context.Background(), path, getOpts)
|
2015-05-24 16:38:49 +00:00
|
|
|
if err != nil {
|
|
|
|
if errorIsMissingKey(err) {
|
|
|
|
return []string{}, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
out := make([]string, len(response.Node.Nodes))
|
|
|
|
for i, node := range response.Node.Nodes {
|
|
|
|
|
|
|
|
// etcd keys include the full path, so let's trim the prefix directory
|
|
|
|
// path.
|
|
|
|
name := strings.TrimPrefix(node.Key, path)
|
|
|
|
|
|
|
|
// Check if this node is itself a directory. If it is, add a trailing
|
|
|
|
// slash; if it isn't remove the node file prefix.
|
|
|
|
if node.Dir {
|
|
|
|
out[i] = name + "/"
|
|
|
|
} else {
|
|
|
|
out[i] = name[1:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return out, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// nodePath returns an etcd filepath based on the given key.
|
|
|
|
func (b *EtcdBackend) nodePath(key string) string {
|
|
|
|
return filepath.Join(b.path, filepath.Dir(key), EtcdNodeFilePrefix+filepath.Base(key))
|
|
|
|
}
|
|
|
|
|
|
|
|
// nodePathDir returns an etcd directory path based on the given key.
|
|
|
|
func (b *EtcdBackend) nodePathDir(key string) string {
|
|
|
|
return filepath.Join(b.path, key) + "/"
|
|
|
|
}
|
2015-05-31 19:02:11 +00:00
|
|
|
|
|
|
|
// nodePathLock returns an etcd directory path used specifically for semaphore
|
|
|
|
// indicies based on the given key.
|
|
|
|
func (b *EtcdBackend) nodePathLock(key string) string {
|
|
|
|
return filepath.Join(b.path, filepath.Dir(key), EtcdNodeLockPrefix+filepath.Base(key)+"/")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lock is used for mutual exclusion based on the given key.
|
|
|
|
func (c *EtcdBackend) LockWith(key, value string) (Lock, error) {
|
|
|
|
return &EtcdLock{
|
2015-11-16 06:12:06 +00:00
|
|
|
kAPI: c.kAPI,
|
2015-06-02 15:03:17 +00:00
|
|
|
value: value,
|
|
|
|
semaphoreDirKey: c.nodePathLock(key),
|
2015-05-31 19:02:11 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// EtcdLock emplements a lock using and etcd backend.
|
|
|
|
type EtcdLock struct {
|
2015-11-16 06:12:06 +00:00
|
|
|
kAPI client.KeysAPI
|
2015-06-02 15:03:17 +00:00
|
|
|
value, semaphoreDirKey, semaphoreKey string
|
|
|
|
lock sync.Mutex
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// addSemaphoreKey aquires a new ordered semaphore key.
|
|
|
|
func (c *EtcdLock) addSemaphoreKey() (string, uint64, error) {
|
|
|
|
// CreateInOrder is an atomic operation that can be used to enqueue a
|
|
|
|
// request onto a semaphore. In the rest of the comments, we refer to the
|
|
|
|
// resulting key as a "semaphore key".
|
|
|
|
// https://coreos.com/etcd/docs/2.0.8/api.html#atomically-creating-in-order-keys
|
2015-11-16 06:12:06 +00:00
|
|
|
opts := &client.CreateInOrderOptions{
|
|
|
|
TTL: EtcdLockTTL,
|
|
|
|
}
|
|
|
|
response, err := c.kAPI.CreateInOrder(context.Background(), c.semaphoreDirKey, c.value, opts)
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2015-11-16 06:12:06 +00:00
|
|
|
return response.Node.Key, response.Index, nil
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
2015-09-09 16:33:07 +00:00
|
|
|
// renewSemaphoreKey renews an existing semaphore key.
|
|
|
|
func (c *EtcdLock) renewSemaphoreKey() (string, uint64, error) {
|
2015-11-16 06:12:06 +00:00
|
|
|
setOpts := &client.SetOptions{
|
2016-01-27 22:15:52 +00:00
|
|
|
TTL: EtcdLockTTL,
|
2015-11-16 06:12:06 +00:00
|
|
|
PrevExist: client.PrevExist,
|
|
|
|
}
|
|
|
|
response, err := c.kAPI.Set(context.Background(), c.semaphoreKey, c.value, setOpts)
|
2015-09-09 16:33:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2015-11-16 06:12:06 +00:00
|
|
|
return response.Node.Key, response.Index, nil
|
2015-09-09 16:33:07 +00:00
|
|
|
}
|
|
|
|
|
2015-06-02 15:03:17 +00:00
|
|
|
// getSemaphoreKey determines which semaphore key holder has aquired the lock
|
|
|
|
// and its value.
|
|
|
|
func (c *EtcdLock) getSemaphoreKey() (string, string, uint64, error) {
|
2015-05-31 19:02:11 +00:00
|
|
|
// Get the list of waiters in order to see if we are next.
|
2015-11-16 06:12:06 +00:00
|
|
|
getOpts := &client.GetOptions{
|
|
|
|
Recursive: false,
|
2016-01-27 22:15:52 +00:00
|
|
|
Sort: true,
|
2015-11-16 06:12:06 +00:00
|
|
|
}
|
|
|
|
response, err := c.kAPI.Get(context.Background(), c.semaphoreDirKey, getOpts)
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
2015-06-02 15:03:17 +00:00
|
|
|
return "", "", 0, err
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure the list isn't empty.
|
|
|
|
if response.Node.Nodes.Len() == 0 {
|
2015-11-16 06:12:06 +00:00
|
|
|
return "", "", response.Index, nil
|
2015-06-02 15:03:17 +00:00
|
|
|
}
|
2015-11-16 06:12:06 +00:00
|
|
|
return response.Node.Nodes[0].Key, response.Node.Nodes[0].Value, response.Index, nil
|
2015-06-02 15:03:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// isHeld determines if we are the current holders of the lock.
|
|
|
|
func (c *EtcdLock) isHeld() (bool, error) {
|
|
|
|
if c.semaphoreKey == "" {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Get the key of the curren holder of the lock.
|
2015-06-02 15:03:17 +00:00
|
|
|
currentSemaphoreKey, _, _, err := c.getSemaphoreKey()
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
return c.semaphoreKey == currentSemaphoreKey, nil
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// assertHeld determines whether or not we are the current holders of the lock
|
|
|
|
// and returns an EtcdLockNotHeldError if we are not.
|
2015-06-02 15:03:17 +00:00
|
|
|
func (c *EtcdLock) assertHeld() error {
|
|
|
|
held, err := c.isHeld()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Check if we don't hold the lock.
|
2015-06-02 15:03:17 +00:00
|
|
|
if !held {
|
|
|
|
return EtcdLockNotHeldError
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// assertNotHeld determines whether or not we are the current holders of the
|
|
|
|
// lock and returns an EtcdLockHeldError if we are.
|
2015-06-02 15:03:17 +00:00
|
|
|
func (c *EtcdLock) assertNotHeld() error {
|
|
|
|
held, err := c.isHeld()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Check if we hold the lock.
|
2015-06-02 15:03:17 +00:00
|
|
|
if held {
|
|
|
|
return EtcdLockHeldError
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-09-09 16:33:07 +00:00
|
|
|
// periodically renew our semaphore key so that it doesn't expire
|
|
|
|
func (c *EtcdLock) periodicallyRenewSemaphoreKey(stopCh chan struct{}) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-time.After(EtcdLockRenewInterval):
|
|
|
|
c.renewSemaphoreKey()
|
|
|
|
case <-stopCh:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-11-05 14:47:50 +00:00
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// watchForKeyRemoval continuously watches a single non-directory key starting
|
|
|
|
// from the provided etcd index and closes the provided channel when it's
|
|
|
|
// deleted, expires, or appears to be missing.
|
2015-06-02 15:03:17 +00:00
|
|
|
func (c *EtcdLock) watchForKeyRemoval(key string, etcdIndex uint64, closeCh chan struct{}) {
|
|
|
|
retries := EtcdWatchRetryMax
|
|
|
|
|
|
|
|
for {
|
|
|
|
// Start a non-recursive watch of the given key.
|
2015-11-16 06:12:06 +00:00
|
|
|
w := c.kAPI.Watcher(key, &client.WatcherOptions{AfterIndex: etcdIndex, Recursive: false})
|
|
|
|
response, err := w.Next(context.TODO())
|
2015-06-02 15:03:17 +00:00
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
// If the key is just missing, we can exit the loop.
|
|
|
|
if errorIsMissingKey(err) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the error is something else, there's nothing we can do but retry
|
|
|
|
// the watch. Check that we still have retries left.
|
|
|
|
retries -= 1
|
|
|
|
if retries == 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sleep for a period of time to avoid slamming etcd.
|
|
|
|
time.Sleep(EtcdWatchRetryInterval)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the key we are concerned with has been removed. If it has, we
|
|
|
|
// can exit the loop.
|
|
|
|
if response.Node.Key == key &&
|
|
|
|
(response.Action == "delete" || response.Action == "expire") {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the etcd index.
|
2015-11-16 06:12:06 +00:00
|
|
|
etcdIndex = response.Index + 1
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Regardless of what happened, we need to close the close channel.
|
2015-06-02 15:03:17 +00:00
|
|
|
close(closeCh)
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Lock attempts to aquire the lock by waiting for a new semaphore key in etcd
|
|
|
|
// to become the first in the queue and will block until it is successful or
|
|
|
|
// it recieves a signal on the provided channel. The returned channel will be
|
|
|
|
// closed when the lock is lost, either by an explicit call to Unlock or by
|
|
|
|
// the associated semaphore key in etcd otherwise being deleted or expiring.
|
|
|
|
//
|
|
|
|
// If the lock is currently held by this instance of EtcdLock, Lock will
|
|
|
|
// return an EtcdLockHeldError error.
|
2015-09-15 08:18:43 +00:00
|
|
|
func (c *EtcdLock) Lock(stopCh <-chan struct{}) (doneCh <-chan struct{}, retErr error) {
|
2015-05-31 19:02:11 +00:00
|
|
|
// Get the local lock before interacting with etcd.
|
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
|
|
|
|
// Check if the lock is already held.
|
2015-09-14 10:30:15 +00:00
|
|
|
if err := c.assertNotHeld(); err != nil {
|
2015-06-02 15:03:17 +00:00
|
|
|
return nil, err
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add a new semaphore key that we will track.
|
|
|
|
semaphoreKey, _, err := c.addSemaphoreKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c.semaphoreKey = semaphoreKey
|
|
|
|
|
|
|
|
// Get the current semaphore key.
|
2015-06-02 15:03:17 +00:00
|
|
|
currentSemaphoreKey, _, currentEtcdIndex, err := c.getSemaphoreKey()
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create an etcd-compatible boolean stop channel from the provided
|
|
|
|
// interface stop channel.
|
2015-11-16 06:12:06 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2015-05-31 19:02:11 +00:00
|
|
|
go func() {
|
2015-06-02 15:03:17 +00:00
|
|
|
<-stopCh
|
2015-11-16 06:12:06 +00:00
|
|
|
cancel()
|
2015-05-31 19:02:11 +00:00
|
|
|
}()
|
2015-11-16 06:12:06 +00:00
|
|
|
defer cancel()
|
2015-05-31 19:02:11 +00:00
|
|
|
|
2015-09-09 16:33:07 +00:00
|
|
|
// Create a channel to signal when we lose the semaphore key.
|
|
|
|
done := make(chan struct{})
|
2015-09-11 13:30:12 +00:00
|
|
|
defer func() {
|
2015-09-15 08:18:43 +00:00
|
|
|
if retErr != nil {
|
2015-09-11 13:17:23 +00:00
|
|
|
close(done)
|
|
|
|
}
|
2015-09-11 13:30:12 +00:00
|
|
|
}()
|
2015-09-11 13:17:23 +00:00
|
|
|
|
2015-09-09 16:33:07 +00:00
|
|
|
go c.periodicallyRenewSemaphoreKey(done)
|
|
|
|
|
2015-05-31 19:02:11 +00:00
|
|
|
// Loop until the we current semaphore key matches ours.
|
|
|
|
for semaphoreKey != currentSemaphoreKey {
|
2015-09-14 10:30:15 +00:00
|
|
|
var err error
|
2015-05-31 19:02:11 +00:00
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
// Start a watch of the entire lock directory
|
|
|
|
w := c.kAPI.Watcher(c.semaphoreDirKey, &client.WatcherOptions{AfterIndex: currentEtcdIndex, Recursive: true})
|
|
|
|
response, err := w.Next(ctx)
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
// If the error is not an etcd error, we can assume it's a notification
|
|
|
|
// of the stop channel having closed. In this scenario, we also want to
|
|
|
|
// remove our semaphore key as we are no longer waiting to aquire the
|
|
|
|
// lock.
|
2015-11-16 06:12:06 +00:00
|
|
|
if _, ok := err.(*client.Error); !ok {
|
|
|
|
delOpts := &client.DeleteOptions{
|
|
|
|
Recursive: false,
|
|
|
|
}
|
|
|
|
_, err = c.kAPI.Delete(context.Background(), c.semaphoreKey, delOpts)
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure the index we are waiting for has not been removed. If it has,
|
|
|
|
// this is an error and nothing else needs to be done.
|
|
|
|
if response.Node.Key == semaphoreKey &&
|
|
|
|
(response.Action == "delete" || response.Action == "expire") {
|
2015-09-14 10:30:15 +00:00
|
|
|
return nil, EtcdSemaphoreKeyRemovedError
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get the current semaphore key and etcd index.
|
2015-06-02 15:03:17 +00:00
|
|
|
currentSemaphoreKey, _, currentEtcdIndex, err = c.getSemaphoreKey()
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 06:12:06 +00:00
|
|
|
go c.watchForKeyRemoval(c.semaphoreKey, currentEtcdIndex, done)
|
2015-06-02 15:03:17 +00:00
|
|
|
return done, nil
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Unlock releases the lock by deleting the associated semaphore key in etcd.
|
|
|
|
//
|
|
|
|
// If the lock is not currently held by this instance of EtcdLock, Unlock will
|
|
|
|
// return an EtcdLockNotHeldError error.
|
2015-05-31 19:02:11 +00:00
|
|
|
func (c *EtcdLock) Unlock() error {
|
|
|
|
// Get the local lock before interacting with etcd.
|
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
|
2015-06-02 15:03:17 +00:00
|
|
|
// Check that the lock is held.
|
|
|
|
if err := c.assertHeld(); err != nil {
|
|
|
|
return err
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete our semaphore key.
|
2015-11-16 06:12:06 +00:00
|
|
|
delOpts := &client.DeleteOptions{
|
|
|
|
Recursive: false,
|
|
|
|
}
|
|
|
|
if _, err := c.kAPI.Delete(context.Background(), c.semaphoreKey, delOpts); err != nil {
|
2015-05-31 19:02:11 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-06-02 22:00:06 +00:00
|
|
|
// Value checks whether or not the lock is held by any instance of EtcdLock,
|
|
|
|
// including this one, and returns the current value.
|
2015-05-31 19:02:11 +00:00
|
|
|
func (c *EtcdLock) Value() (bool, string, error) {
|
2015-06-02 15:03:17 +00:00
|
|
|
semaphoreKey, semaphoreValue, _, err := c.getSemaphoreKey()
|
2015-05-31 19:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if semaphoreKey == "" {
|
2015-06-02 15:03:17 +00:00
|
|
|
return false, "", nil
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|
2015-06-02 15:03:17 +00:00
|
|
|
return true, semaphoreValue, nil
|
2015-05-31 19:02:11 +00:00
|
|
|
}
|