| 1 |
package consul |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"strings" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/xordataexchange/crypt/backend" |
| 9 |
|
| 10 |
"github.com/armon/consul-api" |
| 11 |
) |
| 12 |
|
| 13 |
type Client struct { |
| 14 |
client *consulapi.KV |
| 15 |
waitIndex uint64 |
| 16 |
} |
| 17 |
|
| 18 |
func New(machines []string) (*Client, error) { |
| 19 |
conf := consulapi.DefaultConfig() |
| 20 |
if len(machines) > 0 { |
| 21 |
conf.Address = machines[0] |
| 22 |
} |
| 23 |
client, err := consulapi.NewClient(conf) |
| 24 |
if err != nil { |
| 25 |
return nil, err |
| 26 |
} |
| 27 |
return &Client{client.KV(), 0}, nil |
| 28 |
} |
| 29 |
|
| 30 |
func (c *Client) Get(key string) ([]byte, error) { |
| 31 |
kv, _, err := c.client.Get(key, nil) |
| 32 |
if err != nil { |
| 33 |
return nil, err |
| 34 |
} |
| 35 |
if kv == nil { |
| 36 |
return nil, fmt.Errorf("Key ( %s ) was not found.", key) |
| 37 |
} |
| 38 |
return kv.Value, nil |
| 39 |
} |
| 40 |
|
| 41 |
func (c *Client) List(key string) (backend.KVPairs, error) { |
| 42 |
pairs, _, err := c.client.List(key, nil) |
| 43 |
if err != nil { |
| 44 |
return nil, err |
| 45 |
} |
| 46 |
if err != nil { |
| 47 |
return nil, err |
| 48 |
} |
| 49 |
ret := make(backend.KVPairs, len(pairs), len(pairs)) |
| 50 |
for i, kv := range pairs { |
| 51 |
ret[i] = &backend.KVPair{Key: kv.Key, Value: kv.Value} |
| 52 |
} |
| 53 |
return ret, nil |
| 54 |
} |
| 55 |
|
| 56 |
func (c *Client) Set(key string, value []byte) error { |
| 57 |
key = strings.TrimPrefix(key, "/") |
| 58 |
kv := &consulapi.KVPair{ |
| 59 |
Key: key, |
| 60 |
Value: value, |
| 61 |
} |
| 62 |
_, err := c.client.Put(kv, nil) |
| 63 |
return err |
| 64 |
} |
| 65 |
|
| 66 |
func (c *Client) Watch(key string, stop chan bool) <-chan *backend.Response { |
| 67 |
respChan := make(chan *backend.Response, 0) |
| 68 |
go func() { |
| 69 |
for { |
| 70 |
opts := consulapi.QueryOptions{ |
| 71 |
WaitIndex: c.waitIndex, |
| 72 |
} |
| 73 |
keypair, meta, err := c.client.Get(key, &opts) |
| 74 |
if keypair == nil && err == nil { |
| 75 |
err = fmt.Errorf("Key ( %s ) was not found.", key) |
| 76 |
} |
| 77 |
if err != nil { |
| 78 |
respChan <- &backend.Response{nil, err} |
| 79 |
time.Sleep(time.Second * 5) |
| 80 |
continue |
| 81 |
} |
| 82 |
c.waitIndex = meta.LastIndex |
| 83 |
respChan <- &backend.Response{keypair.Value, nil} |
| 84 |
} |
| 85 |
}() |
| 86 |
return respChan |
| 87 |
} |