datastore.go 11 KB

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