datastore.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. package datastore
  2. import (
  3. "fmt"
  4. "log"
  5. "reflect"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/docker/docker/libnetwork/discoverapi"
  10. "github.com/docker/docker/libnetwork/types"
  11. "github.com/docker/libkv"
  12. "github.com/docker/libkv/store"
  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
  108. GlobalScope = "global"
  109. // SwarmScope is not indicating a datastore location. It is defined here
  110. // along with the other two scopes just for consistency.
  111. SwarmScope = "swarm"
  112. defaultPrefix = "/var/lib/docker/network/files"
  113. )
  114. const (
  115. // NetworkKeyPrefix is the prefix for network key in the kv store
  116. NetworkKeyPrefix = "network"
  117. // EndpointKeyPrefix is the prefix for endpoint key in the kv store
  118. EndpointKeyPrefix = "endpoint"
  119. )
  120. var defaultRootChain = []string{"docker", "network", "v1.0"}
  121. var rootChain = defaultRootChain
  122. // DefaultScope returns a default scope config for clients to use.
  123. func DefaultScope(dataDir string) ScopeCfg {
  124. var dbpath string
  125. if dataDir == "" {
  126. dbpath = defaultPrefix + "/local-kv.db"
  127. } else {
  128. dbpath = dataDir + "/network/files/local-kv.db"
  129. }
  130. return ScopeCfg{
  131. Client: ScopeClientCfg{
  132. Provider: string(store.BOLTDB),
  133. Address: dbpath,
  134. Config: &store.Config{
  135. Bucket: "libnetwork",
  136. ConnectionTimeout: time.Minute,
  137. },
  138. },
  139. }
  140. }
  141. // IsValid checks if the scope config has valid configuration.
  142. func (cfg *ScopeCfg) IsValid() bool {
  143. if cfg == nil ||
  144. strings.TrimSpace(cfg.Client.Provider) == "" ||
  145. strings.TrimSpace(cfg.Client.Address) == "" {
  146. return false
  147. }
  148. return true
  149. }
  150. // Key provides convenient method to create a Key
  151. func Key(key ...string) string {
  152. keychain := append(rootChain, key...)
  153. str := strings.Join(keychain, "/")
  154. return str + "/"
  155. }
  156. // ParseKey provides convenient method to unpack the key to complement the Key function
  157. func ParseKey(key string) ([]string, error) {
  158. chain := strings.Split(strings.Trim(key, "/"), "/")
  159. // The key must at least be equal to the rootChain in order to be considered as valid
  160. if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
  161. return nil, types.BadRequestErrorf("invalid Key : %s", key)
  162. }
  163. return chain[len(rootChain):], nil
  164. }
  165. // newClient used to connect to KV Store
  166. func newClient(kv string, addr string, config *store.Config) (DataStore, error) {
  167. if config == nil {
  168. config = &store.Config{}
  169. }
  170. var addrs []string
  171. if kv == string(store.BOLTDB) {
  172. // Parse file path
  173. addrs = strings.Split(addr, ",")
  174. } else {
  175. // Parse URI
  176. parts := strings.SplitN(addr, "/", 2)
  177. addrs = strings.Split(parts[0], ",")
  178. // Add the custom prefix to the root chain
  179. if len(parts) == 2 {
  180. rootChain = append([]string{parts[1]}, defaultRootChain...)
  181. }
  182. }
  183. s, err := libkv.NewStore(store.Backend(kv), addrs, config)
  184. if err != nil {
  185. return nil, err
  186. }
  187. ds := &datastore{scope: LocalScope, store: s, active: true, watchCh: make(chan struct{}), sequential: true}
  188. ds.cache = newCache(ds)
  189. return ds, nil
  190. }
  191. // NewDataStore creates a new instance of LibKV data store
  192. func NewDataStore(cfg ScopeCfg) (DataStore, error) {
  193. if cfg.Client.Provider == "" || cfg.Client.Address == "" {
  194. cfg = DefaultScope("")
  195. }
  196. return newClient(cfg.Client.Provider, cfg.Client.Address, cfg.Client.Config)
  197. }
  198. // NewDataStoreFromConfig creates a new instance of LibKV data store starting from the datastore config data
  199. func NewDataStoreFromConfig(dsc discoverapi.DatastoreConfigData) (DataStore, error) {
  200. var (
  201. ok bool
  202. sCfgP *store.Config
  203. )
  204. sCfgP, ok = dsc.Config.(*store.Config)
  205. if !ok && dsc.Config != nil {
  206. return nil, fmt.Errorf("cannot parse store configuration: %v", dsc.Config)
  207. }
  208. scopeCfg := ScopeCfg{
  209. Client: ScopeClientCfg{
  210. Address: dsc.Address,
  211. Provider: dsc.Provider,
  212. Config: sCfgP,
  213. },
  214. }
  215. ds, err := NewDataStore(scopeCfg)
  216. if err != nil {
  217. return nil, fmt.Errorf("failed to construct datastore client from datastore configuration %v: %v", dsc, err)
  218. }
  219. return ds, err
  220. }
  221. func (ds *datastore) Close() {
  222. ds.store.Close()
  223. }
  224. func (ds *datastore) Scope() string {
  225. return ds.scope
  226. }
  227. func (ds *datastore) Active() bool {
  228. return ds.active
  229. }
  230. func (ds *datastore) Watchable() bool {
  231. return ds.scope != LocalScope
  232. }
  233. func (ds *datastore) Watch(kvObject KVObject, stopCh <-chan struct{}) (<-chan KVObject, error) {
  234. sCh := make(chan struct{})
  235. ctor, ok := kvObject.(KVConstructor)
  236. if !ok {
  237. return nil, fmt.Errorf("error watching object type %T, object does not implement KVConstructor interface", kvObject)
  238. }
  239. kvpCh, err := ds.store.Watch(Key(kvObject.Key()...), sCh)
  240. if err != nil {
  241. return nil, err
  242. }
  243. kvoCh := make(chan KVObject)
  244. go func() {
  245. retry_watch:
  246. var err error
  247. // Make sure to get a new instance of watch channel
  248. ds.Lock()
  249. watchCh := ds.watchCh
  250. ds.Unlock()
  251. loop:
  252. for {
  253. select {
  254. case <-stopCh:
  255. close(sCh)
  256. return
  257. case kvPair := <-kvpCh:
  258. // If the backend KV store gets reset libkv's go routine
  259. // for the watch can exit resulting in a nil value in
  260. // channel.
  261. if kvPair == nil {
  262. ds.Lock()
  263. ds.active = false
  264. ds.Unlock()
  265. break loop
  266. }
  267. dstO := ctor.New()
  268. if err = dstO.SetValue(kvPair.Value); err != nil {
  269. log.Printf("Could not unmarshal kvpair value = %s", string(kvPair.Value))
  270. break
  271. }
  272. dstO.SetIndex(kvPair.LastIndex)
  273. kvoCh <- dstO
  274. }
  275. }
  276. // Wait on watch channel for a re-trigger when datastore becomes active
  277. <-watchCh
  278. kvpCh, err = ds.store.Watch(Key(kvObject.Key()...), sCh)
  279. if err != nil {
  280. log.Printf("Could not watch the key %s in store: %v", Key(kvObject.Key()...), err)
  281. }
  282. goto retry_watch
  283. }()
  284. return kvoCh, nil
  285. }
  286. func (ds *datastore) RestartWatch() {
  287. ds.Lock()
  288. defer ds.Unlock()
  289. ds.active = true
  290. watchCh := ds.watchCh
  291. ds.watchCh = make(chan struct{})
  292. close(watchCh)
  293. }
  294. func (ds *datastore) KVStore() store.Store {
  295. return ds.store
  296. }
  297. // PutObjectAtomic adds a new Record based on an object into the datastore
  298. func (ds *datastore) PutObjectAtomic(kvObject KVObject) error {
  299. var (
  300. previous *store.KVPair
  301. pair *store.KVPair
  302. err error
  303. )
  304. if ds.sequential {
  305. ds.Lock()
  306. defer ds.Unlock()
  307. }
  308. if kvObject == nil {
  309. return types.BadRequestErrorf("invalid KV Object : nil")
  310. }
  311. kvObjValue := kvObject.Value()
  312. if kvObjValue == nil {
  313. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  314. }
  315. if kvObject.Skip() {
  316. goto add_cache
  317. }
  318. if kvObject.Exists() {
  319. previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  320. } else {
  321. previous = nil
  322. }
  323. _, pair, err = ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
  324. if err != nil {
  325. if err == store.ErrKeyExists {
  326. return ErrKeyModified
  327. }
  328. return err
  329. }
  330. kvObject.SetIndex(pair.LastIndex)
  331. add_cache:
  332. if ds.cache != nil {
  333. // If persistent store is skipped, sequencing needs to
  334. // happen in cache.
  335. return ds.cache.add(kvObject, kvObject.Skip())
  336. }
  337. return nil
  338. }
  339. // PutObject adds a new Record based on an object into the datastore
  340. func (ds *datastore) PutObject(kvObject KVObject) error {
  341. if ds.sequential {
  342. ds.Lock()
  343. defer ds.Unlock()
  344. }
  345. if kvObject == nil {
  346. return types.BadRequestErrorf("invalid KV Object : nil")
  347. }
  348. if kvObject.Skip() {
  349. goto add_cache
  350. }
  351. if err := ds.putObjectWithKey(kvObject, kvObject.Key()...); err != nil {
  352. return err
  353. }
  354. add_cache:
  355. if ds.cache != nil {
  356. // If persistent store is skipped, sequencing needs to
  357. // happen in cache.
  358. return ds.cache.add(kvObject, kvObject.Skip())
  359. }
  360. return nil
  361. }
  362. func (ds *datastore) putObjectWithKey(kvObject KVObject, key ...string) error {
  363. kvObjValue := kvObject.Value()
  364. if kvObjValue == nil {
  365. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  366. }
  367. return ds.store.Put(Key(key...), kvObjValue, nil)
  368. }
  369. // GetObject returns a record matching the key
  370. func (ds *datastore) GetObject(key string, o KVObject) error {
  371. if ds.sequential {
  372. ds.Lock()
  373. defer ds.Unlock()
  374. }
  375. if ds.cache != nil {
  376. return ds.cache.get(key, o)
  377. }
  378. kvPair, err := ds.store.Get(key)
  379. if err != nil {
  380. return err
  381. }
  382. if err := o.SetValue(kvPair.Value); err != nil {
  383. return err
  384. }
  385. // Make sure the object has a correct view of the DB index in
  386. // case we need to modify it and update the DB.
  387. o.SetIndex(kvPair.LastIndex)
  388. return nil
  389. }
  390. func (ds *datastore) ensureParent(parent string) error {
  391. exists, err := ds.store.Exists(parent)
  392. if err != nil {
  393. return err
  394. }
  395. if exists {
  396. return nil
  397. }
  398. return ds.store.Put(parent, []byte{}, &store.WriteOptions{IsDir: true})
  399. }
  400. func (ds *datastore) List(key string, kvObject KVObject) ([]KVObject, error) {
  401. if ds.sequential {
  402. ds.Lock()
  403. defer ds.Unlock()
  404. }
  405. if ds.cache != nil {
  406. return ds.cache.list(kvObject)
  407. }
  408. var kvol []KVObject
  409. cb := func(key string, val KVObject) {
  410. kvol = append(kvol, val)
  411. }
  412. err := ds.iterateKVPairsFromStore(key, kvObject, cb)
  413. if err != nil {
  414. return nil, err
  415. }
  416. return kvol, nil
  417. }
  418. func (ds *datastore) iterateKVPairsFromStore(key string, kvObject KVObject, callback func(string, KVObject)) error {
  419. // Bail out right away if the kvObject does not implement KVConstructor
  420. ctor, ok := kvObject.(KVConstructor)
  421. if !ok {
  422. return fmt.Errorf("error listing objects, object does not implement KVConstructor interface")
  423. }
  424. // Make sure the parent key exists
  425. if err := ds.ensureParent(key); err != nil {
  426. return err
  427. }
  428. kvList, err := ds.store.List(key)
  429. if err != nil {
  430. return err
  431. }
  432. for _, kvPair := range kvList {
  433. if len(kvPair.Value) == 0 {
  434. continue
  435. }
  436. dstO := ctor.New()
  437. if err := dstO.SetValue(kvPair.Value); err != nil {
  438. return err
  439. }
  440. // Make sure the object has a correct view of the DB index in
  441. // case we need to modify it and update the DB.
  442. dstO.SetIndex(kvPair.LastIndex)
  443. callback(kvPair.Key, dstO)
  444. }
  445. return nil
  446. }
  447. func (ds *datastore) Map(key string, kvObject KVObject) (map[string]KVObject, error) {
  448. if ds.sequential {
  449. ds.Lock()
  450. defer ds.Unlock()
  451. }
  452. kvol := make(map[string]KVObject)
  453. cb := func(key string, val KVObject) {
  454. // Trim the leading & trailing "/" to make it consistent across all stores
  455. kvol[strings.Trim(key, "/")] = val
  456. }
  457. err := ds.iterateKVPairsFromStore(key, kvObject, cb)
  458. if err != nil {
  459. return nil, err
  460. }
  461. return kvol, nil
  462. }
  463. // DeleteObject unconditionally deletes a record from the store
  464. func (ds *datastore) DeleteObject(kvObject KVObject) error {
  465. if ds.sequential {
  466. ds.Lock()
  467. defer ds.Unlock()
  468. }
  469. // cleanup the cache first
  470. if ds.cache != nil {
  471. // If persistent store is skipped, sequencing needs to
  472. // happen in cache.
  473. ds.cache.del(kvObject, kvObject.Skip())
  474. }
  475. if kvObject.Skip() {
  476. return nil
  477. }
  478. return ds.store.Delete(Key(kvObject.Key()...))
  479. }
  480. // DeleteObjectAtomic performs atomic delete on a record
  481. func (ds *datastore) DeleteObjectAtomic(kvObject KVObject) error {
  482. if ds.sequential {
  483. ds.Lock()
  484. defer ds.Unlock()
  485. }
  486. if kvObject == nil {
  487. return types.BadRequestErrorf("invalid KV Object : nil")
  488. }
  489. previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  490. if kvObject.Skip() {
  491. goto del_cache
  492. }
  493. if _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous); err != nil {
  494. if err == store.ErrKeyExists {
  495. return ErrKeyModified
  496. }
  497. return err
  498. }
  499. del_cache:
  500. // cleanup the cache only if AtomicDelete went through successfully
  501. if ds.cache != nil {
  502. // If persistent store is skipped, sequencing needs to
  503. // happen in cache.
  504. return ds.cache.del(kvObject, kvObject.Skip())
  505. }
  506. return nil
  507. }
  508. // DeleteTree unconditionally deletes a record from the store
  509. func (ds *datastore) DeleteTree(kvObject KVObject) error {
  510. if ds.sequential {
  511. ds.Lock()
  512. defer ds.Unlock()
  513. }
  514. // cleanup the cache first
  515. if ds.cache != nil {
  516. // If persistent store is skipped, sequencing needs to
  517. // happen in cache.
  518. ds.cache.del(kvObject, kvObject.Skip())
  519. }
  520. if kvObject.Skip() {
  521. return nil
  522. }
  523. return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
  524. }