datastore.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package datastore
  2. import (
  3. "fmt"
  4. "log"
  5. "reflect"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/docker/libkv"
  10. "github.com/docker/libkv/store"
  11. "github.com/docker/libnetwork/discoverapi"
  12. "github.com/docker/libnetwork/types"
  13. )
  14. //DataStore exported
  15. type DataStore interface {
  16. // GetObject gets data from datastore and unmarshals to the specified object
  17. GetObject(key string, o KVObject) error
  18. // PutObject adds a new Record based on an object into the datastore
  19. PutObject(kvObject KVObject) error
  20. // PutObjectAtomic provides an atomic add and update operation for a Record
  21. PutObjectAtomic(kvObject KVObject) error
  22. // DeleteObject deletes a record
  23. DeleteObject(kvObject KVObject) error
  24. // DeleteObjectAtomic performs an atomic delete operation
  25. DeleteObjectAtomic(kvObject KVObject) error
  26. // DeleteTree deletes a record
  27. DeleteTree(kvObject KVObject) error
  28. // Watchable returns whether the store is watchable or not
  29. Watchable() bool
  30. // Watch for changes on a KVObject
  31. Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error)
  32. // RestartWatch retriggers stopped Watches
  33. RestartWatch()
  34. // Active returns if the store is active
  35. Active() bool
  36. // List returns of a list of KVObjects belonging to the parent
  37. // key. The caller must pass a KVObject of the same type as
  38. // the objects that need to be listed
  39. List(string, KVObject) ([]KVObject, error)
  40. // Map returns a Map of KVObjects
  41. Map(key string, kvObject KVObject) (map[string]KVObject, error)
  42. // Scope returns the scope of the store
  43. Scope() string
  44. // KVStore returns access to the KV Store
  45. KVStore() store.Store
  46. // Close closes the data store
  47. Close()
  48. }
  49. // ErrKeyModified is raised for an atomic update when the update is working on a stale state
  50. var (
  51. ErrKeyModified = store.ErrKeyModified
  52. ErrKeyNotFound = store.ErrKeyNotFound
  53. )
  54. type datastore struct {
  55. scope string
  56. store store.Store
  57. cache *cache
  58. watchCh chan struct{}
  59. active bool
  60. sequential bool
  61. sync.Mutex
  62. }
  63. // KVObject is Key/Value interface used by objects to be part of the DataStore
  64. type KVObject interface {
  65. // Key method lets an object provide the Key to be used in KV Store
  66. Key() []string
  67. // KeyPrefix method lets an object return immediate parent key that can be used for tree walk
  68. KeyPrefix() []string
  69. // Value method lets an object marshal its content to be stored in the KV store
  70. Value() []byte
  71. // SetValue is used by the datastore to set the object's value when loaded from the data store.
  72. SetValue([]byte) error
  73. // Index method returns the latest DB Index as seen by the object
  74. Index() uint64
  75. // SetIndex method allows the datastore to store the latest DB Index into the object
  76. SetIndex(uint64)
  77. // True if the object exists in the datastore, false if it hasn't been stored yet.
  78. // When SetIndex() is called, the object has been stored.
  79. Exists() bool
  80. // DataScope indicates the storage scope of the KV object
  81. DataScope() string
  82. // Skip provides a way for a KV Object to avoid persisting it in the KV Store
  83. Skip() bool
  84. }
  85. // KVConstructor interface defines methods which can construct a KVObject from another.
  86. type KVConstructor interface {
  87. // New returns a new object which is created based on the
  88. // source object
  89. New() KVObject
  90. // CopyTo deep copies the contents of the implementing object
  91. // to the passed destination object
  92. CopyTo(KVObject) error
  93. }
  94. // ScopeCfg represents Datastore configuration.
  95. type ScopeCfg struct {
  96. Client ScopeClientCfg
  97. }
  98. // ScopeClientCfg represents Datastore Client-only mode configuration
  99. type ScopeClientCfg struct {
  100. Provider string
  101. Address string
  102. Config *store.Config
  103. }
  104. const (
  105. // LocalScope indicates to store the KV object in local datastore such as boltdb
  106. LocalScope = "local"
  107. // GlobalScope indicates to store the KV object in global datastore such as consul/etcd/zookeeper
  108. GlobalScope = "global"
  109. defaultPrefix = "/var/lib/docker/network/files"
  110. )
  111. const (
  112. // NetworkKeyPrefix is the prefix for network key in the kv store
  113. NetworkKeyPrefix = "network"
  114. // EndpointKeyPrefix is the prefix for endpoint key in the kv store
  115. EndpointKeyPrefix = "endpoint"
  116. )
  117. var (
  118. defaultScopes = makeDefaultScopes()
  119. )
  120. func makeDefaultScopes() map[string]*ScopeCfg {
  121. def := make(map[string]*ScopeCfg)
  122. def[LocalScope] = &ScopeCfg{
  123. Client: ScopeClientCfg{
  124. Provider: string(store.BOLTDB),
  125. Address: defaultPrefix + "/local-kv.db",
  126. Config: &store.Config{
  127. Bucket: "libnetwork",
  128. ConnectionTimeout: time.Minute,
  129. },
  130. },
  131. }
  132. return def
  133. }
  134. var defaultRootChain = []string{"docker", "network", "v1.0"}
  135. var rootChain = defaultRootChain
  136. // DefaultScopes returns a map of default scopes and its config for clients to use.
  137. func DefaultScopes(dataDir string) map[string]*ScopeCfg {
  138. if dataDir != "" {
  139. defaultScopes[LocalScope].Client.Address = dataDir + "/network/files/local-kv.db"
  140. return defaultScopes
  141. }
  142. defaultScopes[LocalScope].Client.Address = defaultPrefix + "/local-kv.db"
  143. return defaultScopes
  144. }
  145. // IsValid checks if the scope config has valid configuration.
  146. func (cfg *ScopeCfg) IsValid() bool {
  147. if cfg == nil ||
  148. strings.TrimSpace(cfg.Client.Provider) == "" ||
  149. strings.TrimSpace(cfg.Client.Address) == "" {
  150. return false
  151. }
  152. return true
  153. }
  154. //Key provides convenient method to create a Key
  155. func Key(key ...string) string {
  156. keychain := append(rootChain, key...)
  157. str := strings.Join(keychain, "/")
  158. return str + "/"
  159. }
  160. //ParseKey provides convenient method to unpack the key to complement the Key function
  161. func ParseKey(key string) ([]string, error) {
  162. chain := strings.Split(strings.Trim(key, "/"), "/")
  163. // The key must atleast be equal to the rootChain in order to be considered as valid
  164. if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
  165. return nil, types.BadRequestErrorf("invalid Key : %s", key)
  166. }
  167. return chain[len(rootChain):], nil
  168. }
  169. // newClient used to connect to KV Store
  170. func newClient(scope string, kv string, addr string, config *store.Config, cached bool) (DataStore, error) {
  171. if cached && scope != LocalScope {
  172. return nil, fmt.Errorf("caching supported only for scope %s", LocalScope)
  173. }
  174. sequential := false
  175. if scope == LocalScope {
  176. sequential = true
  177. }
  178. if config == nil {
  179. config = &store.Config{}
  180. }
  181. var addrs []string
  182. if kv == string(store.BOLTDB) {
  183. // Parse file path
  184. addrs = strings.Split(addr, ",")
  185. } else {
  186. // Parse URI
  187. parts := strings.SplitN(addr, "/", 2)
  188. addrs = strings.Split(parts[0], ",")
  189. // Add the custom prefix to the root chain
  190. if len(parts) == 2 {
  191. rootChain = append([]string{parts[1]}, defaultRootChain...)
  192. }
  193. }
  194. store, err := libkv.NewStore(store.Backend(kv), addrs, config)
  195. if err != nil {
  196. return nil, err
  197. }
  198. ds := &datastore{scope: scope, store: store, active: true, watchCh: make(chan struct{}), sequential: sequential}
  199. if cached {
  200. ds.cache = newCache(ds)
  201. }
  202. return ds, nil
  203. }
  204. // NewDataStore creates a new instance of LibKV data store
  205. func NewDataStore(scope string, cfg *ScopeCfg) (DataStore, error) {
  206. if cfg == nil || cfg.Client.Provider == "" || cfg.Client.Address == "" {
  207. c, ok := defaultScopes[scope]
  208. if !ok || c.Client.Provider == "" || c.Client.Address == "" {
  209. return nil, fmt.Errorf("unexpected scope %s without configuration passed", scope)
  210. }
  211. cfg = c
  212. }
  213. var cached bool
  214. if scope == LocalScope {
  215. cached = true
  216. }
  217. return newClient(scope, cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config, cached)
  218. }
  219. // NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data
  220. func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) {
  221. var (
  222. ok bool
  223. sCfgP *store.Config
  224. )
  225. sCfgP, ok = dsc.Config.(*store.Config)
  226. if !ok && dsc.Config != nil {
  227. return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config)
  228. }
  229. scopeCfg := &ScopeCfg{
  230. Client: ScopeClientCfg{
  231. Address: dsc.Address,
  232. Provider: dsc.Provider,
  233. Config: sCfgP,
  234. },
  235. }
  236. ds, err := NewDataStore(dsc.Scope, scopeCfg)
  237. if err != nil {
  238. return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err)
  239. }
  240. return ds, err
  241. }
  242. func (ds *datastore) Close() {
  243. ds.store.Close()
  244. }
  245. func (ds *datastore) Scope() string {
  246. return ds.scope
  247. }
  248. func (ds *datastore) Active() bool {
  249. return ds.active
  250. }
  251. func (ds *datastore) Watchable() bool {
  252. return ds.scope != LocalScope
  253. }
  254. func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) {
  255. sCh := make(chan struct{})
  256. ctor, ok := kvObject.(KVConstructor)
  257. if !ok {
  258. return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject)
  259. }
  260. kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh)
  261. if err != nil {
  262. return nil, err
  263. }
  264. kvoCh := make(chan KVObject)
  265. go func() {
  266. retry_watch:
  267. var err error
  268. // Make sure to get a new instance of watch channel
  269. ds.Lock()
  270. watchCh := ds.watchCh
  271. ds.Unlock()
  272. loop:
  273. for {
  274. select {
  275. case <-stopCh:
  276. close(sCh)
  277. return
  278. case kvPair := <-kvpCh:
  279. // If the backend KV store gets reset libkv's go routine
  280. // for the watch can exit resulting in a nil value in
  281. // channel.
  282. if kvPair == nil {
  283. ds.Lock()
  284. ds.active = false
  285. ds.Unlock()
  286. break loop
  287. }
  288. dstO := ctor.New()
  289. if err = dstO.SetValue(kvPair.Value); err != nil {
  290. log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value))
  291. break
  292. }
  293. dstO.SetIndex(kvPair.LastIndex)
  294. kvoCh <- dstO
  295. }
  296. }
  297. // Wait on watch channel for a re-trigger when datastore becomes active
  298. <-watchCh
  299. kvpCh, err = ds.store.Watch(Key(kvObject.Key()...), sCh)
  300. if err != nil {
  301. log.Printf("Could not watch the key %s in store: %v", Key(kvObject.Key()...), err)
  302. }
  303. goto retry_watch
  304. }()
  305. return kvoCh, nil
  306. }
  307. func (ds *datastore) RestartWatch() {
  308. ds.Lock()
  309. defer ds.Unlock()
  310. ds.active = true
  311. watchCh := ds.watchCh
  312. ds.watchCh = make(chan struct{})
  313. close(watchCh)
  314. }
  315. func (ds *datastore) KVStore() store.Store {
  316. return ds.store
  317. }
  318. // PutObjectAtomic adds a new Record based on an object into the datastore
  319. func (ds *datastore) PutObjectAtomic(kvObject KVObject) error {
  320. var (
  321. previous *store.KVPair
  322. pair *store.KVPair
  323. err error
  324. )
  325. if ds.sequential {
  326. ds.Lock()
  327. defer ds.Unlock()
  328. }
  329. if kvObject == nil {
  330. return types.BadRequestErrorf("invalid KV Object : nil")
  331. }
  332. kvObjValue := kvObject.Value()
  333. if kvObjValue == nil {
  334. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  335. }
  336. if kvObject.Skip() {
  337. goto add_cache
  338. }
  339. if kvObject.Exists() {
  340. previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  341. } else {
  342. previous = nil
  343. }
  344. _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
  345. if err != nil {
  346. if err == store.ErrKeyExists {
  347. return ErrKeyModified
  348. }
  349. return err
  350. }
  351. kvObject.SetIndex(pair.LastIndex)
  352. add_cache:
  353. if ds.cache != nil {
  354. // If persistent store is skipped, sequencing needs to
  355. // happen in cache.
  356. return ds.cache.add(kvObject, kvObject.Skip())
  357. }
  358. return nil
  359. }
  360. // PutObject adds a new Record based on an object into the datastore
  361. func (ds *datastore) PutObject(kvObject KVObject) error {
  362. if ds.sequential {
  363. ds.Lock()
  364. defer ds.Unlock()
  365. }
  366. if kvObject == nil {
  367. return types.BadRequestErrorf("invalid KV Object : nil")
  368. }
  369. if kvObject.Skip() {
  370. goto add_cache
  371. }
  372. if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil {
  373. return err
  374. }
  375. add_cache:
  376. if ds.cache != nil {
  377. // If persistent store is skipped, sequencing needs to
  378. // happen in cache.
  379. return ds.cache.add(kvObject, kvObject.Skip())
  380. }
  381. return nil
  382. }
  383. func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error {
  384. kvObjValue := kvObject.Value()
  385. if kvObjValue == nil {
  386. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  387. }
  388. return ds.store.Put(Key(key...), kvObjValue, nil)
  389. }
  390. // GetObject returns a record matching the key
  391. func (ds *datastore) GetObject(key string, o KVObject) error {
  392. if ds.sequential {
  393. ds.Lock()
  394. defer ds.Unlock()
  395. }
  396. if ds.cache != nil {
  397. return ds.cache.get(key, o)
  398. }
  399. kvPair, err := ds.store.Get(key)
  400. if err != nil {
  401. return err
  402. }
  403. if err := o.SetValue(kvPair.Value); err != nil {
  404. return err
  405. }
  406. // Make sure the object has a correct view of the DB index in
  407. // case we need to modify it and update the DB.
  408. o.SetIndex(kvPair.LastIndex)
  409. return nil
  410. }
  411. func (ds *datastore) ensureParent(parent string) error {
  412. exists, err := ds.store.Exists(parent)
  413. if err != nil {
  414. return err
  415. }
  416. if exists {
  417. return nil
  418. }
  419. return ds.store.Put(parent, []byte{}, &store.WriteOptions{IsDir: true})
  420. }
  421. func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) {
  422. if ds.sequential {
  423. ds.Lock()
  424. defer ds.Unlock()
  425. }
  426. if ds.cache != nil {
  427. return ds.cache.list(kvObject)
  428. }
  429. var kvol []KVObject
  430. cb := func(key string, val KVObject) {
  431. kvol = append(kvol, val)
  432. }
  433. err := ds.iterateKVPairsFromStore(key, kvObject, cb)
  434. if err != nil {
  435. return nil, err
  436. }
  437. return kvol, nil
  438. }
  439. func (ds *datastore) iterateKVPairsFromStore(key string, kvObject KVObject, callback func(string, KVObject)) error {
  440. // Bail out right away if the kvObject does not implement KVConstructor
  441. ctor, ok := kvObject.(KVConstructor)
  442. if !ok {
  443. return fmt.Errorf("error listing objects, object does not implement KVConstructor interface")
  444. }
  445. // Make sure the parent key exists
  446. if err := ds.ensureParent(key); err != nil {
  447. return err
  448. }
  449. kvList, err := ds.store.List(key)
  450. if err != nil {
  451. return err
  452. }
  453. for _, kvPair := range kvList {
  454. if len(kvPair.Value) == 0 {
  455. continue
  456. }
  457. dstO := ctor.New()
  458. if err := dstO.SetValue(kvPair.Value); err != nil {
  459. return err
  460. }
  461. // Make sure the object has a correct view of the DB index in
  462. // case we need to modify it and update the DB.
  463. dstO.SetIndex(kvPair.LastIndex)
  464. callback(kvPair.Key, dstO)
  465. }
  466. return nil
  467. }
  468. func (ds *datastore) Map(key string, kvObject KVObject) (map[string]KVObject, error) {
  469. if ds.sequential {
  470. ds.Lock()
  471. defer ds.Unlock()
  472. }
  473. kvol := make(map[string]KVObject)
  474. cb := func(key string, val KVObject) {
  475. // Trim the leading & trailing "/" to make it consistent across all stores
  476. kvol[strings.Trim(key, "/")] = val
  477. }
  478. err := ds.iterateKVPairsFromStore(key, kvObject, cb)
  479. if err != nil {
  480. return nil, err
  481. }
  482. return kvol, nil
  483. }
  484. // DeleteObject unconditionally deletes a record from the store
  485. func (ds *datastore) DeleteObject(kvObject KVObject) error {
  486. if ds.sequential {
  487. ds.Lock()
  488. defer ds.Unlock()
  489. }
  490. // cleaup the cache first
  491. if ds.cache != nil {
  492. // If persistent store is skipped, sequencing needs to
  493. // happen in cache.
  494. ds.cache.del(kvObject, kvObject.Skip())
  495. }
  496. if kvObject.Skip() {
  497. return nil
  498. }
  499. return ds.store.Delete(Key(kvObject.Key()...))
  500. }
  501. // DeleteObjectAtomic performs atomic delete on a record
  502. func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error {
  503. if ds.sequential {
  504. ds.Lock()
  505. defer ds.Unlock()
  506. }
  507. if kvObject == nil {
  508. return types.BadRequestErrorf("invalid KV Object : nil")
  509. }
  510. previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  511. if kvObject.Skip() {
  512. goto del_cache
  513. }
  514. if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil {
  515. if err == store.ErrKeyExists {
  516. return ErrKeyModified
  517. }
  518. return err
  519. }
  520. del_cache:
  521. // cleanup the cache only if AtomicDelete went through successfully
  522. if ds.cache != nil {
  523. // If persistent store is skipped, sequencing needs to
  524. // happen in cache.
  525. return ds.cache.del(kvObject, kvObject.Skip())
  526. }
  527. return nil
  528. }
  529. // DeleteTree unconditionally deletes a record from the store
  530. func (ds *datastore) DeleteTree(kvObject KVObject) error {
  531. if ds.sequential {
  532. ds.Lock()
  533. defer ds.Unlock()
  534. }
  535. // cleaup the cache first
  536. if ds.cache != nil {
  537. // If persistent store is skipped, sequencing needs to
  538. // happen in cache.
  539. ds.cache.del(kvObject, kvObject.Skip())
  540. }
  541. if kvObject.Skip() {
  542. return nil
  543. }
  544. return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
  545. }