datastore.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package datastore
  2. import (
  3. "reflect"
  4. "strings"
  5. "github.com/docker/libkv"
  6. "github.com/docker/libkv/store"
  7. "github.com/docker/libnetwork/config"
  8. "github.com/docker/libnetwork/types"
  9. )
  10. //DataStore exported
  11. type DataStore interface {
  12. // GetObject gets data from datastore and unmarshals to the specified object
  13. GetObject(key string, o KV) error
  14. // PutObject adds a new Record based on an object into the datastore
  15. PutObject(kvObject KV) error
  16. // PutObjectAtomic provides an atomic add and update operation for a Record
  17. PutObjectAtomic(kvObject KV) error
  18. // DeleteObject deletes a record
  19. DeleteObject(kvObject KV) error
  20. // DeleteObjectAtomic performs an atomic delete operation
  21. DeleteObjectAtomic(kvObject KV) error
  22. // DeleteTree deletes a record
  23. DeleteTree(kvObject KV) error
  24. // KVStore returns access to the KV Store
  25. KVStore() store.Store
  26. }
  27. // ErrKeyModified is raised for an atomic update when the update is working on a stale state
  28. var (
  29. ErrKeyModified = store.ErrKeyModified
  30. ErrKeyNotFound = store.ErrKeyNotFound
  31. )
  32. type datastore struct {
  33. store store.Store
  34. }
  35. //KV Key Value interface used by objects to be part of the DataStore
  36. type KV interface {
  37. // Key method lets an object to provide the Key to be used in KV Store
  38. Key() []string
  39. // KeyPrefix method lets an object to return immediate parent key that can be used for tree walk
  40. KeyPrefix() []string
  41. // Value method lets an object to marshal its content to be stored in the KV store
  42. Value() []byte
  43. // SetValue is used by the datastore to set the object's value when loaded from the data store.
  44. SetValue([]byte) error
  45. // Index method returns the latest DB Index as seen by the object
  46. Index() uint64
  47. // SetIndex method allows the datastore to store the latest DB Index into the object
  48. SetIndex(uint64)
  49. // True if the object exists in the datastore, false if it hasn't been stored yet.
  50. // When SetIndex() is called, the object has been stored.
  51. Exists() bool
  52. }
  53. const (
  54. // NetworkKeyPrefix is the prefix for network key in the kv store
  55. NetworkKeyPrefix = "network"
  56. // EndpointKeyPrefix is the prefix for endpoint key in the kv store
  57. EndpointKeyPrefix = "endpoint"
  58. )
  59. var rootChain = []string{"docker", "libnetwork"}
  60. //Key provides convenient method to create a Key
  61. func Key(key ...string) string {
  62. keychain := append(rootChain, key...)
  63. str := strings.Join(keychain, "/")
  64. return str + "/"
  65. }
  66. //ParseKey provides convenient method to unpack the key to complement the Key function
  67. func ParseKey(key string) ([]string, error) {
  68. chain := strings.Split(strings.Trim(key, "/"), "/")
  69. // The key must atleast be equal to the rootChain in order to be considered as valid
  70. if len(chain) <= len(rootChain) || !reflect.DeepEqual(chain[0:len(rootChain)], rootChain) {
  71. return nil, types.BadRequestErrorf("invalid Key : %s", key)
  72. }
  73. return chain[len(rootChain):], nil
  74. }
  75. // newClient used to connect to KV Store
  76. func newClient(kv string, addrs string) (DataStore, error) {
  77. store, err := libkv.NewStore(store.Backend(kv), []string{addrs}, &store.Config{})
  78. if err != nil {
  79. return nil, err
  80. }
  81. ds := &datastore{store: store}
  82. return ds, nil
  83. }
  84. // NewDataStore creates a new instance of LibKV data store
  85. func NewDataStore(cfg *config.DatastoreCfg) (DataStore, error) {
  86. if cfg == nil {
  87. return nil, types.BadRequestErrorf("invalid configuration passed to datastore")
  88. }
  89. // TODO : cfg.Embedded case
  90. return newClient(cfg.Client.Provider, cfg.Client.Address)
  91. }
  92. // NewCustomDataStore can be used by clients to plugin cusom datatore that adhers to store.Store
  93. func NewCustomDataStore(customStore store.Store) DataStore {
  94. return &datastore{store: customStore}
  95. }
  96. func (ds *datastore) KVStore() store.Store {
  97. return ds.store
  98. }
  99. // PutObjectAtomic adds a new Record based on an object into the datastore
  100. func (ds *datastore) PutObjectAtomic(kvObject KV) error {
  101. if kvObject == nil {
  102. return types.BadRequestErrorf("invalid KV Object : nil")
  103. }
  104. kvObjValue := kvObject.Value()
  105. if kvObjValue == nil {
  106. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  107. }
  108. var previous *store.KVPair
  109. if kvObject.Exists() {
  110. previous = &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  111. } else {
  112. previous = nil
  113. }
  114. _, pair, err := ds.store.AtomicPut(Key(kvObject.Key()...), kvObjValue, previous, nil)
  115. if err != nil {
  116. return err
  117. }
  118. kvObject.SetIndex(pair.LastIndex)
  119. return nil
  120. }
  121. // PutObject adds a new Record based on an object into the datastore
  122. func (ds *datastore) PutObject(kvObject KV) error {
  123. if kvObject == nil {
  124. return types.BadRequestErrorf("invalid KV Object : nil")
  125. }
  126. return ds.putObjectWithKey(kvObject, kvObject.Key()...)
  127. }
  128. func (ds *datastore) putObjectWithKey(kvObject KV, key ...string) error {
  129. kvObjValue := kvObject.Value()
  130. if kvObjValue == nil {
  131. return types.BadRequestErrorf("invalid KV Object with a nil Value for key %s", Key(kvObject.Key()...))
  132. }
  133. return ds.store.Put(Key(key...), kvObjValue, nil)
  134. }
  135. // GetObject returns a record matching the key
  136. func (ds *datastore) GetObject(key string, o KV) error {
  137. kvPair, err := ds.store.Get(key)
  138. if err != nil {
  139. return err
  140. }
  141. err = o.SetValue(kvPair.Value)
  142. if err != nil {
  143. return err
  144. }
  145. // Make sure the object has a correct view of the DB index in case we need to modify it
  146. // and update the DB.
  147. o.SetIndex(kvPair.LastIndex)
  148. return nil
  149. }
  150. // DeleteObject unconditionally deletes a record from the store
  151. func (ds *datastore) DeleteObject(kvObject KV) error {
  152. return ds.store.Delete(Key(kvObject.Key()...))
  153. }
  154. // DeleteObjectAtomic performs atomic delete on a record
  155. func (ds *datastore) DeleteObjectAtomic(kvObject KV) error {
  156. if kvObject == nil {
  157. return types.BadRequestErrorf("invalid KV Object : nil")
  158. }
  159. previous := &store.KVPair{Key: Key(kvObject.Key()...), LastIndex: kvObject.Index()}
  160. _, err := ds.store.AtomicDelete(Key(kvObject.Key()...), previous)
  161. return err
  162. }
  163. // DeleteTree unconditionally deletes a record from the store
  164. func (ds *datastore) DeleteTree(kvObject KV) error {
  165. return ds.store.DeleteTree(Key(kvObject.KeyPrefix()...))
  166. }