datastore.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package datastore
  2. import (
  3. "fmt"
  4. "log"
  5. "reflect"
  6. "strings"
  7. "github.com/docker/libkv"
  8. "github.com/docker/libkv/store"
  9. "github.com/docker/libkv/store/boltdb"
  10. "github.com/docker/libkv/store/consul"
  11. "github.com/docker/libkv/store/etcd"
  12. "github.com/docker/libkv/store/zookeeper"
  13. "github.com/docker/libnetwork/types"
  14. )
  15. //DataStore exported
  16. type DataStore interface {
  17. // GetObject gets data from datastore and unmarshals to the specified object
  18. GetObject(key string, o KVObject) error
  19. // PutObject adds a new Record based on an object into the datastore
  20. PutObject(kvObject KVObject) error
  21. // PutObjectAtomic provides an atomic add and update operation for a Record
  22. PutObjectAtomic(kvObject KVObject) error
  23. // DeleteObject deletes a record
  24. DeleteObject(kvObject KVObject) error
  25. // DeleteObjectAtomic performs an atomic delete operation
  26. DeleteObjectAtomic(kvObject KVObject) error
  27. // DeleteTree deletes a record
  28. DeleteTree(kvObject KVObject) error
  29. // Watchable returns whether the store is watchable are not
  30. Watchable() bool
  31. // Watch for changes on a KVObject
  32. Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error)
  33. // List returns of a list of KVObjects belonging to the parent
  34. // key. The caller must pass a KVObject of the same type as
  35. // the objects that need to be listed
  36. List(string, KVObject) ([]KVObject, error)
  37. // Scope returns the scope of the store
  38. Scope() string
  39. // KVStore returns access to the KV Store
  40. KVStore() store.Store
  41. // Close closes the data store
  42. Close()
  43. }
  44. // ErrKeyModified is raised for an atomic update when the update is working on a stale state
  45. var (
  46. ErrKeyModified = store.ErrKeyModified
  47. ErrKeyNotFound = store.ErrKeyNotFound
  48. )
  49. type datastore struct {
  50. scope string
  51. store store.Store
  52. cache *cache
  53. }
  54. // KVObject is Key/Value interface used by objects to be part of the DataStore
  55. type KVObject interface {
  56. // Key method lets an object to provide the Key to be used in KV Store
  57. Key() []string
  58. // KeyPrefix method lets an object to return immediate parent key that can be used for tree walk
  59. KeyPrefix() []string
  60. // Value method lets an object to marshal its content to be stored in the KV store
  61. Value() []byte
  62. // SetValue is used by the datastore to set the object's value when loaded from the data store.
  63. SetValue([]byte) error
  64. // Index method returns the latest DB Index as seen by the object
  65. Index() uint64
  66. // SetIndex method allows the datastore to store the latest DB Index into the object
  67. SetIndex(uint64)
  68. // True if the object exists in the datastore, false if it hasn't been stored yet.
  69. // When SetIndex() is called, the object has been stored.
  70. Exists() bool
  71. // DataScope indicates the storage scope of the KV object
  72. DataScope() string
  73. // Skip provides a way for a KV Object to avoid persisting it in the KV Store
  74. Skip() bool
  75. }
  76. // KVConstructor interface defines methods which can construct a KVObject from another.
  77. type KVConstructor interface {
  78. // New returns a new object which is created based on the
  79. // source object
  80. New() KVObject
  81. // CopyTo deep copies the contents of the implementing object
  82. // to the passed destination object
  83. CopyTo(KVObject) error
  84. }
  85. // ScopeCfg represents Datastore configuration.
  86. type ScopeCfg struct {
  87. Client ScopeClientCfg
  88. }
  89. // ScopeClientCfg represents Datastore Client-only mode configuration
  90. type ScopeClientCfg struct {
  91. Provider string
  92. Address string
  93. Config *store.Config
  94. }
  95. const (
  96. // LocalScope indicates to store the KV object in local datastore such as boltdb
  97. LocalScope = "local"
  98. // GlobalScope indicates to store the KV object in global datastore such as consul/etcd/zookeeper
  99. GlobalScope = "global"
  100. defaultPrefix = "/var/lib/docker/network/files"
  101. )
  102. const (
  103. // NetworkKeyPrefix is the prefix for network key in the kv store
  104. NetworkKeyPrefix = "network"
  105. // EndpointKeyPrefix is the prefix for endpoint key in the kv store
  106. EndpointKeyPrefix = "endpoint"
  107. )
  108. var (
  109. defaultScopes = makeDefaultScopes()
  110. )
  111. func makeDefaultScopes() map[string]*ScopeCfg {
  112. def := make(map[string]*ScopeCfg)
  113. def[LocalScope] = &ScopeCfg{
  114. Client: ScopeClientCfg{
  115. Provider: "boltdb",
  116. Address: defaultPrefix + "/local-kv.db",
  117. Config: &store.Config{
  118. Bucket: "libnetwork",
  119. },
  120. },
  121. }
  122. return def
  123. }
  124. var rootChain = []string{"docker", "network", "v1.0"}
  125. func init() {
  126. consul.Register()
  127. zookeeper.Register()
  128. etcd.Register()
  129. boltdb.Register()
  130. }
  131. // DefaultScopes returns a map of default scopes and it's config for clients to use.
  132. func DefaultScopes(dataDir string) map[string]*ScopeCfg {
  133. if dataDir != "" {
  134. defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db"
  135. return defaultScopes
  136. }
  137. defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db"
  138. return defaultScopes
  139. }
  140. // IsValid checks if the scope config has valid configuration.
  141. func (cfg *ScopeCfg) IsValid() bool {
  142. if cfg == nil ||
  143. strings.TrimSpace(cfg.Client.Provider) == "" ||
  144. strings.TrimSpace(cfg.Client.Address) == "" {
  145. return false
  146. }
  147. return true
  148. }
  149. //Key provides convenient method to create a Key
  150. func Key(key ...string) string {
  151. keychain := append(rootChain, key...)
  152. str := strings.Join(keychain, "/")
  153. return str + "/"
  154. }
  155. //ParseKey provides convenient method to unpack the key to complement the Key function
  156. func ParseKey(key string) ([]string, error) {
  157. chain := strings.Split(strings.Trim(key, "/"), "/")
  158. // The key must atleast be equal to the rootChain in order to be considered as valid
  159. if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
  160. return nil, types.BadRequestErrorf("invalid Key : %s", key)
  161. }
  162. return chain[len(rootChain):], nil
  163. }
  164. // newClient used to connect to KV Store
  165. func newClient(scope string, kv string, addrs string, config *store.Config, cached bool) (DataStore, error) {
  166. if cached && scope != LocalScope {
  167. return nil, fmt.Errorf("caching supported only for scope %s", LocalScope)
  168. }
  169. if config == nil {
  170. config = &store.Config{}
  171. }
  172. store, err := libkv.NewStore(store.Backend(kv), []string{addrs}, config)
  173. if err != nil {
  174. return nil, err
  175. }
  176. ds := &datastore{scope: scope, store: store}
  177. if cached {
  178. ds.cache = newCache(ds)
  179. }
  180. return ds, nil
  181. }
  182. // NewDataStore creates a new instance of LibKV data store
  183. func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) {
  184. if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" {
  185. c, ok := defaultScopes[scope]
  186. if !ok || c.Client.Provider == "" || c.Client.Address == "" {
  187. return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope)
  188. }
  189. cfg = c
  190. }
  191. var cached bool
  192. if scope == LocalScope {
  193. cached = true
  194. }
  195. return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached)
  196. }
  197. func (ds *datastore) Close() {
  198. ds.store.Close()
  199. }
  200. func (ds *datastore) Scope() string {
  201. return ds.scope
  202. }
  203. func (ds *datastore) Watchable() bool {
  204. return ds.scope != LocalScope
  205. }
  206. func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) {
  207. sCh := make(chan struct{})
  208. ctor, ok := kvObject.(KVConstructor)
  209. if !ok {
  210. return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject)
  211. }
  212. kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh)
  213. if err != nil {
  214. return nil, err
  215. }
  216. kvoCh := make(chan KVObject)
  217. go func() {
  218. for {
  219. select {
  220. case <-stopCh:
  221. close(sCh)
  222. return
  223. case kvPair := <-kvpCh:
  224. dstO := ctor.New()
  225. if err := dstO.SetValue(kvPair.Value); err != nil {
  226. log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value))
  227. break
  228. }
  229. dstO.SetIndex(kvPair.LastIndex)
  230. kvoCh <- dstO
  231. }
  232. }
  233. }()
  234. return kvoCh, nil
  235. }
  236. func (ds *datastore) KVStore() store.Store {
  237. return ds.store
  238. }
  239. // PutObjectAtomic adds a new Record based on an object into the datastore
  240. func (ds *datastore) PutObjectAtomic(kvObject KVObject) error {
  241. var (
  242. previous *store.KVPair
  243. pair *store.KVPair
  244. err error
  245. )
  246. if kvObject == nil {
  247. return types.BadRequestErrorf("invalid KV Object : nil")
  248. }
  249. kvObjValue := kvObject.Value()
  250. if kvObjValue == nil {
  251. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  252. }
  253. if kvObject.Skip() {
  254. goto add_cache
  255. }
  256. if kvObject.Exists() {
  257. previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  258. } else {
  259. previous = nil
  260. }
  261. _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
  262. if err != nil {
  263. return err
  264. }
  265. kvObject.SetIndex(pair.LastIndex)
  266. add_cache:
  267. if ds.cache != nil {
  268. return ds.cache.add(kvObject)
  269. }
  270. return nil
  271. }
  272. // PutObject adds a new Record based on an object into the datastore
  273. func (ds *datastore) PutObject(kvObject KVObject) error {
  274. if kvObject == nil {
  275. return types.BadRequestErrorf("invalid KV Object : nil")
  276. }
  277. if kvObject.Skip() {
  278. goto add_cache
  279. }
  280. if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil {
  281. return err
  282. }
  283. add_cache:
  284. if ds.cache != nil {
  285. return ds.cache.add(kvObject)
  286. }
  287. return nil
  288. }
  289. func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error {
  290. kvObjValue := kvObject.Value()
  291. if kvObjValue == nil {
  292. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  293. }
  294. return ds.store.Put(Key(key...), kvObjValue, nil)
  295. }
  296. // GetObject returns a record matching the key
  297. func (ds *datastore) GetObject(key string, o KVObject) error {
  298. if ds.cache != nil {
  299. return ds.cache.get(key, o)
  300. }
  301. kvPair, err := ds.store.Get(key)
  302. if err != nil {
  303. return err
  304. }
  305. if err := o.SetValue(kvPair.Value); err != nil {
  306. return err
  307. }
  308. // Make sure the object has a correct view of the DB index in
  309. // case we need to modify it and update the DB.
  310. o.SetIndex(kvPair.LastIndex)
  311. return nil
  312. }
  313. func (ds *datastore) ensureKey(key string) error {
  314. exists, err := ds.store.Exists(key)
  315. if err != nil {
  316. return err
  317. }
  318. if exists {
  319. return nil
  320. }
  321. return ds.store.Put(key, []byte{}, nil)
  322. }
  323. func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) {
  324. if ds.cache != nil {
  325. return ds.cache.list(kvObject)
  326. }
  327. // Bail out right away if the kvObject does not implement KVConstructor
  328. ctor, ok := kvObject.(KVConstructor)
  329. if !ok {
  330. return nil, fmt.Errorf("error listing objects, object does not implement KVConstructor interface")
  331. }
  332. // Make sure the parent key exists
  333. if err := ds.ensureKey(key); err != nil {
  334. return nil, err
  335. }
  336. kvList, err := ds.store.List(key)
  337. if err != nil {
  338. return nil, err
  339. }
  340. var kvol []KVObject
  341. for _, kvPair := range kvList {
  342. if len(kvPair.Value) == 0 {
  343. continue
  344. }
  345. dstO := ctor.New()
  346. if err := dstO.SetValue(kvPair.Value); err != nil {
  347. return nil, err
  348. }
  349. // Make sure the object has a correct view of the DB index in
  350. // case we need to modify it and update the DB.
  351. dstO.SetIndex(kvPair.LastIndex)
  352. kvol = append(kvol, dstO)
  353. }
  354. return kvol, nil
  355. }
  356. // DeleteObject unconditionally deletes a record from the store
  357. func (ds *datastore) DeleteObject(kvObject KVObject) error {
  358. // cleaup the cache first
  359. if ds.cache != nil {
  360. ds.cache.del(kvObject)
  361. }
  362. if kvObject.Skip() {
  363. return nil
  364. }
  365. return ds.store.Delete(Key(kvObject.Key()...))
  366. }
  367. // DeleteObjectAtomic performs atomic delete on a record
  368. func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error {
  369. if kvObject == nil {
  370. return types.BadRequestErrorf("invalid KV Object : nil")
  371. }
  372. previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  373. if kvObject.Skip() {
  374. goto del_cache
  375. }
  376. if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil {
  377. return err
  378. }
  379. del_cache:
  380. // cleanup the cache only if AtomicDelete went through successfully
  381. if ds.cache != nil {
  382. return ds.cache.del(kvObject)
  383. }
  384. return nil
  385. }
  386. // DeleteTree unconditionally deletes a record from the store
  387. func (ds *datastore) DeleteTree(kvObject KVObject) error {
  388. // cleaup the cache first
  389. if ds.cache != nil {
  390. ds.cache.del(kvObject)
  391. }
  392. if kvObject.Skip() {
  393. return nil
  394. }
  395. return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
  396. }