libkv
is a unified library to interact with different key-value store backends. libkv
was originally part of Docker Swarm v1 in the very first versions of the development. Later, all code related to key-value store discovery services was refactored and moved to www.github.com/docker/libkv.
libkv
allows you to execute CRUD operations and also to watch key-value entries from different backends, so we can use the same code to work with all HA distributed key-value stores, which are Consul, Etcd, and ZooKeeper as shown in the following figure. At the time of writing, libkv also supports a local store implemented using BoltDB.
To start with libkv,
we need to understand how to call its APIs first. Here's the libkv Store
interface in Go, for every store implementation:
type Store interface { Put(key string, value []byte, options *WriteOptions) error Get(key string) (*KVPair, error) Delete(key string) error Exists(key string) (bool, error) Watch(key string, stopCh <-chan struct{}) (<-chan *KVPair, error) WatchTree(directory string, stopCh <-chan struct{}) (<-chan []*KVPair, error) NewLock(key string, options *LockOptions) (Locker, error) List(directory string) ([]*KVPair, error) DeleteTree(directory string) error AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) AtomicDelete(key string, previous *KVPair) (bool, error) Close() }
We need to know how to Put
, Get
, Delete
, and Watch
to basically interact with a store.
Make sure you also have Go and Git installed on your machine and the Git executable is on your PATH. Then, we need to do a number of go get to install dependencies for our program:
$ go get github.com/docker/libkv $ go get github.com/davecgh/go-spew/spew $ go get github.com/hashicorp/consul/api
Here we provide with a skeleton. You need to start a single-node Consul
before you try to run the following program:
# Delete all keys in Consul $ curl -X DELETE http://localhost:8500/v1/kv/?recurse # Compile the program $ go build main.go # Run it $ ./main # Spew is dumping the result for us in details ([]*store.KVPair) (len=1 cap=2) { (*store.KVPair)(0x10e00de0)({ Key: (string) (len=27) "docker/nodes/127.0.0.1:2375", Value: ([]uint8) (len=14 cap=15) { 00000000 31 32 37 2e 30 2e 30 2e 31 3a 32 33 37 35 |127.0.0.1:2375| }, LastIndex: (uint64) 736745 }) }
You can also test getting your value with curl. The value you've put should be there. We should continue playing with the libkv APIs,which are Get
and Delete
. It's left for the readers as an exercise.