datastore.go 12 KB

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