store.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. /*
  2. Copyright 2013 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "path"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. etcdErr "github.com/coreos/etcd/error"
  23. )
  24. // The default version to set when the store is first initialized.
  25. const defaultVersion = 2
  26. var minExpireTime time.Time
  27. func init() {
  28. minExpireTime, _ = time.Parse(time.RFC3339, "2000-01-01T00:00:00Z")
  29. }
  30. type Store interface {
  31. Version() int
  32. Index() uint64
  33. Get(nodePath string, recursive, sorted bool) (*Event, error)
  34. Set(nodePath string, dir bool, value string, expireTime time.Time) (*Event, error)
  35. Update(nodePath string, newValue string, expireTime time.Time) (*Event, error)
  36. Create(nodePath string, dir bool, value string, unique bool,
  37. expireTime time.Time) (*Event, error)
  38. CompareAndSwap(nodePath string, prevValue string, prevIndex uint64,
  39. value string, expireTime time.Time) (*Event, error)
  40. Delete(nodePath string, recursive, dir bool) (*Event, error)
  41. CompareAndDelete(nodePath string, prevValue string, prevIndex uint64) (*Event, error)
  42. Watch(prefix string, recursive, stream bool, sinceIndex uint64) (*Watcher, error)
  43. Save() ([]byte, error)
  44. Recovery(state []byte) error
  45. TotalTransactions() uint64
  46. JsonStats() []byte
  47. DeleteExpiredKeys(cutoff time.Time)
  48. }
  49. type store struct {
  50. Root *node
  51. WatcherHub *watcherHub
  52. CurrentIndex uint64
  53. Stats *Stats
  54. CurrentVersion int
  55. ttlKeyHeap *ttlKeyHeap // need to recovery manually
  56. worldLock sync.RWMutex // stop the world lock
  57. }
  58. func New() Store {
  59. return newStore()
  60. }
  61. func newStore() *store {
  62. s := new(store)
  63. s.CurrentVersion = defaultVersion
  64. s.Root = newDir(s, "/", s.CurrentIndex, nil, "", Permanent)
  65. s.Stats = newStats()
  66. s.WatcherHub = newWatchHub(1000)
  67. s.ttlKeyHeap = newTtlKeyHeap()
  68. return s
  69. }
  70. // Version retrieves current version of the store.
  71. func (s *store) Version() int {
  72. return s.CurrentVersion
  73. }
  74. // Retrieves current of the store
  75. func (s *store) Index() uint64 {
  76. s.worldLock.RLock()
  77. defer s.worldLock.RUnlock()
  78. return s.CurrentIndex
  79. }
  80. // Get returns a get event.
  81. // If recursive is true, it will return all the content under the node path.
  82. // If sorted is true, it will sort the content by keys.
  83. func (s *store) Get(nodePath string, recursive, sorted bool) (*Event, error) {
  84. s.worldLock.RLock()
  85. defer s.worldLock.RUnlock()
  86. nodePath = path.Clean(path.Join("/", nodePath))
  87. n, err := s.internalGet(nodePath)
  88. if err != nil {
  89. s.Stats.Inc(GetFail)
  90. return nil, err
  91. }
  92. e := newEvent(Get, nodePath, n.ModifiedIndex, n.CreatedIndex)
  93. e.Node.loadInternalNode(n, recursive, sorted)
  94. s.Stats.Inc(GetSuccess)
  95. return e, nil
  96. }
  97. // Create creates the node at nodePath. Create will help to create intermediate directories with no ttl.
  98. // If the node has already existed, create will fail.
  99. // If any node on the path is a file, create will fail.
  100. func (s *store) Create(nodePath string, dir bool, value string, unique bool, expireTime time.Time) (*Event, error) {
  101. s.worldLock.Lock()
  102. defer s.worldLock.Unlock()
  103. e, err := s.internalCreate(nodePath, dir, value, unique, false, expireTime, Create)
  104. if err == nil {
  105. s.WatcherHub.notify(e)
  106. s.Stats.Inc(CreateSuccess)
  107. } else {
  108. s.Stats.Inc(CreateFail)
  109. }
  110. return e, err
  111. }
  112. // Set creates or replace the node at nodePath.
  113. func (s *store) Set(nodePath string, dir bool, value string, expireTime time.Time) (*Event, error) {
  114. var err error
  115. s.worldLock.Lock()
  116. defer s.worldLock.Unlock()
  117. defer func() {
  118. if err == nil {
  119. s.Stats.Inc(SetSuccess)
  120. } else {
  121. s.Stats.Inc(SetFail)
  122. }
  123. }()
  124. // Get prevNode value
  125. n, getErr := s.internalGet(nodePath)
  126. if getErr != nil && getErr.ErrorCode != etcdErr.EcodeKeyNotFound {
  127. err = getErr
  128. return nil, err
  129. }
  130. // Set new value
  131. e, err := s.internalCreate(nodePath, dir, value, false, true, expireTime, Set)
  132. if err != nil {
  133. return nil, err
  134. }
  135. // Put prevNode into event
  136. if getErr == nil {
  137. prev := newEvent(Get, nodePath, n.ModifiedIndex, n.CreatedIndex)
  138. prev.Node.loadInternalNode(n, false, false)
  139. e.PrevNode = prev.Node
  140. }
  141. s.WatcherHub.notify(e)
  142. return e, nil
  143. }
  144. // returns user-readable cause of failed comparison
  145. func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) string {
  146. switch which {
  147. case CompareIndexNotMatch:
  148. return fmt.Sprintf("[%v != %v]", prevIndex, n.ModifiedIndex)
  149. case CompareValueNotMatch:
  150. return fmt.Sprintf("[%v != %v]", prevValue, n.Value)
  151. default:
  152. return fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, n.Value, prevIndex, n.ModifiedIndex)
  153. }
  154. }
  155. func (s *store) CompareAndSwap(nodePath string, prevValue string, prevIndex uint64,
  156. value string, expireTime time.Time) (*Event, error) {
  157. s.worldLock.Lock()
  158. defer s.worldLock.Unlock()
  159. nodePath = path.Clean(path.Join("/", nodePath))
  160. // we do not allow the user to change "/"
  161. if nodePath == "/" {
  162. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  163. }
  164. n, err := s.internalGet(nodePath)
  165. if err != nil {
  166. s.Stats.Inc(CompareAndSwapFail)
  167. return nil, err
  168. }
  169. if n.IsDir() { // can only compare and swap file
  170. s.Stats.Inc(CompareAndSwapFail)
  171. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, s.CurrentIndex)
  172. }
  173. // If both of the prevValue and prevIndex are given, we will test both of them.
  174. // Command will be executed, only if both of the tests are successful.
  175. if ok, which := n.Compare(prevValue, prevIndex); !ok {
  176. cause := getCompareFailCause(n, which, prevValue, prevIndex)
  177. s.Stats.Inc(CompareAndSwapFail)
  178. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  179. }
  180. // update etcd index
  181. s.CurrentIndex++
  182. e := newEvent(CompareAndSwap, nodePath, s.CurrentIndex, n.CreatedIndex)
  183. e.PrevNode = n.Repr(false, false)
  184. eNode := e.Node
  185. // if test succeed, write the value
  186. n.Write(value, s.CurrentIndex)
  187. n.UpdateTTL(expireTime)
  188. // copy the value for safety
  189. valueCopy := value
  190. eNode.Value = &valueCopy
  191. eNode.Expiration, eNode.TTL = n.ExpirationAndTTL()
  192. s.WatcherHub.notify(e)
  193. s.Stats.Inc(CompareAndSwapSuccess)
  194. return e, nil
  195. }
  196. // Delete deletes the node at the given path.
  197. // If the node is a directory, recursive must be true to delete it.
  198. func (s *store) Delete(nodePath string, dir, recursive bool) (*Event, error) {
  199. s.worldLock.Lock()
  200. defer s.worldLock.Unlock()
  201. nodePath = path.Clean(path.Join("/", nodePath))
  202. // we do not allow the user to change "/"
  203. if nodePath == "/" {
  204. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  205. }
  206. // recursive implies dir
  207. if recursive == true {
  208. dir = true
  209. }
  210. n, err := s.internalGet(nodePath)
  211. if err != nil { // if the node does not exist, return error
  212. s.Stats.Inc(DeleteFail)
  213. return nil, err
  214. }
  215. nextIndex := s.CurrentIndex + 1
  216. e := newEvent(Delete, nodePath, nextIndex, n.CreatedIndex)
  217. e.PrevNode = n.Repr(false, false)
  218. eNode := e.Node
  219. if n.IsDir() {
  220. eNode.Dir = true
  221. }
  222. callback := func(path string) { // notify function
  223. // notify the watchers with deleted set true
  224. s.WatcherHub.notifyWatchers(e, path, true)
  225. }
  226. err = n.Remove(dir, recursive, callback)
  227. if err != nil {
  228. s.Stats.Inc(DeleteFail)
  229. return nil, err
  230. }
  231. // update etcd index
  232. s.CurrentIndex++
  233. s.WatcherHub.notify(e)
  234. s.Stats.Inc(DeleteSuccess)
  235. return e, nil
  236. }
  237. func (s *store) CompareAndDelete(nodePath string, prevValue string, prevIndex uint64) (*Event, error) {
  238. nodePath = path.Clean(path.Join("/", nodePath))
  239. s.worldLock.Lock()
  240. defer s.worldLock.Unlock()
  241. n, err := s.internalGet(nodePath)
  242. if err != nil { // if the node does not exist, return error
  243. s.Stats.Inc(CompareAndDeleteFail)
  244. return nil, err
  245. }
  246. if n.IsDir() { // can only compare and delete file
  247. s.Stats.Inc(CompareAndSwapFail)
  248. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, s.CurrentIndex)
  249. }
  250. // If both of the prevValue and prevIndex are given, we will test both of them.
  251. // Command will be executed, only if both of the tests are successful.
  252. if ok, which := n.Compare(prevValue, prevIndex); !ok {
  253. cause := getCompareFailCause(n, which, prevValue, prevIndex)
  254. s.Stats.Inc(CompareAndDeleteFail)
  255. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  256. }
  257. // update etcd index
  258. s.CurrentIndex++
  259. e := newEvent(CompareAndDelete, nodePath, s.CurrentIndex, n.CreatedIndex)
  260. e.PrevNode = n.Repr(false, false)
  261. callback := func(path string) { // notify function
  262. // notify the watchers with deleted set true
  263. s.WatcherHub.notifyWatchers(e, path, true)
  264. }
  265. // delete a key-value pair, no error should happen
  266. n.Remove(false, false, callback)
  267. s.WatcherHub.notify(e)
  268. s.Stats.Inc(CompareAndDeleteSuccess)
  269. return e, nil
  270. }
  271. func (s *store) Watch(key string, recursive, stream bool, sinceIndex uint64) (*Watcher, error) {
  272. s.worldLock.RLock()
  273. defer s.worldLock.RUnlock()
  274. key = path.Clean(path.Join("/", key))
  275. nextIndex := s.CurrentIndex + 1
  276. var w *Watcher
  277. var err *etcdErr.Error
  278. if sinceIndex == 0 {
  279. w, err = s.WatcherHub.watch(key, recursive, stream, nextIndex)
  280. } else {
  281. w, err = s.WatcherHub.watch(key, recursive, stream, sinceIndex)
  282. }
  283. if err != nil {
  284. // watchhub do not know the current Index
  285. // we need to attach the currentIndex here
  286. err.Index = s.CurrentIndex
  287. return nil, err
  288. }
  289. return w, nil
  290. }
  291. // walk walks all the nodePath and apply the walkFunc on each directory
  292. func (s *store) walk(nodePath string, walkFunc func(prev *node, component string) (*node, *etcdErr.Error)) (*node, *etcdErr.Error) {
  293. components := strings.Split(nodePath, "/")
  294. curr := s.Root
  295. var err *etcdErr.Error
  296. for i := 1; i < len(components); i++ {
  297. if len(components[i]) == 0 { // ignore empty string
  298. return curr, nil
  299. }
  300. curr, err = walkFunc(curr, components[i])
  301. if err != nil {
  302. return nil, err
  303. }
  304. }
  305. return curr, nil
  306. }
  307. // Update updates the value/ttl of the node.
  308. // If the node is a file, the value and the ttl can be updated.
  309. // If the node is a directory, only the ttl can be updated.
  310. func (s *store) Update(nodePath string, newValue string, expireTime time.Time) (*Event, error) {
  311. s.worldLock.Lock()
  312. defer s.worldLock.Unlock()
  313. nodePath = path.Clean(path.Join("/", nodePath))
  314. // we do not allow the user to change "/"
  315. if nodePath == "/" {
  316. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  317. }
  318. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  319. n, err := s.internalGet(nodePath)
  320. if err != nil { // if the node does not exist, return error
  321. s.Stats.Inc(UpdateFail)
  322. return nil, err
  323. }
  324. e := newEvent(Update, nodePath, nextIndex, n.CreatedIndex)
  325. e.PrevNode = n.Repr(false, false)
  326. eNode := e.Node
  327. if n.IsDir() && len(newValue) != 0 {
  328. // if the node is a directory, we cannot update value to non-empty
  329. s.Stats.Inc(UpdateFail)
  330. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  331. }
  332. n.Write(newValue, nextIndex)
  333. if n.IsDir() {
  334. eNode.Dir = true
  335. } else {
  336. // copy the value for safety
  337. newValueCopy := newValue
  338. eNode.Value = &newValueCopy
  339. }
  340. // update ttl
  341. n.UpdateTTL(expireTime)
  342. eNode.Expiration, eNode.TTL = n.ExpirationAndTTL()
  343. s.WatcherHub.notify(e)
  344. s.Stats.Inc(UpdateSuccess)
  345. s.CurrentIndex = nextIndex
  346. return e, nil
  347. }
  348. func (s *store) internalCreate(nodePath string, dir bool, value string, unique, replace bool,
  349. expireTime time.Time, action string) (*Event, error) {
  350. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  351. if unique { // append unique item under the node path
  352. nodePath += "/" + strconv.FormatUint(nextIndex, 10)
  353. }
  354. nodePath = path.Clean(path.Join("/", nodePath))
  355. // we do not allow the user to change "/"
  356. if nodePath == "/" {
  357. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", currIndex)
  358. }
  359. // Assume expire times that are way in the past are not valid.
  360. // This can occur when the time is serialized to JSON and read back in.
  361. if expireTime.Before(minExpireTime) {
  362. expireTime = Permanent
  363. }
  364. dirName, nodeName := path.Split(nodePath)
  365. // walk through the nodePath, create dirs and get the last directory node
  366. d, err := s.walk(dirName, s.checkDir)
  367. if err != nil {
  368. s.Stats.Inc(SetFail)
  369. err.Index = currIndex
  370. return nil, err
  371. }
  372. e := newEvent(action, nodePath, nextIndex, nextIndex)
  373. eNode := e.Node
  374. n, _ := d.GetChild(nodeName)
  375. // force will try to replace a existing file
  376. if n != nil {
  377. if replace {
  378. if n.IsDir() {
  379. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  380. }
  381. e.PrevNode = n.Repr(false, false)
  382. n.Remove(false, false, nil)
  383. } else {
  384. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, currIndex)
  385. }
  386. }
  387. if !dir { // create file
  388. // copy the value for safety
  389. valueCopy := value
  390. eNode.Value = &valueCopy
  391. n = newKV(s, nodePath, value, nextIndex, d, "", expireTime)
  392. } else { // create directory
  393. eNode.Dir = true
  394. n = newDir(s, nodePath, nextIndex, d, "", expireTime)
  395. }
  396. // we are sure d is a directory and does not have the children with name n.Name
  397. d.Add(n)
  398. // node with TTL
  399. if !n.IsPermanent() {
  400. s.ttlKeyHeap.push(n)
  401. eNode.Expiration, eNode.TTL = n.ExpirationAndTTL()
  402. }
  403. s.CurrentIndex = nextIndex
  404. return e, nil
  405. }
  406. // InternalGet gets the node of the given nodePath.
  407. func (s *store) internalGet(nodePath string) (*node, *etcdErr.Error) {
  408. nodePath = path.Clean(path.Join("/", nodePath))
  409. walkFunc := func(parent *node, name string) (*node, *etcdErr.Error) {
  410. if !parent.IsDir() {
  411. err := etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path, s.CurrentIndex)
  412. return nil, err
  413. }
  414. child, ok := parent.Children[name]
  415. if ok {
  416. return child, nil
  417. }
  418. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name), s.CurrentIndex)
  419. }
  420. f, err := s.walk(nodePath, walkFunc)
  421. if err != nil {
  422. return nil, err
  423. }
  424. return f, nil
  425. }
  426. // deleteExpiredKyes will delete all
  427. func (s *store) DeleteExpiredKeys(cutoff time.Time) {
  428. s.worldLock.Lock()
  429. defer s.worldLock.Unlock()
  430. for {
  431. node := s.ttlKeyHeap.top()
  432. if node == nil || node.ExpireTime.After(cutoff) {
  433. break
  434. }
  435. s.CurrentIndex++
  436. e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex)
  437. e.PrevNode = node.Repr(false, false)
  438. callback := func(path string) { // notify function
  439. // notify the watchers with deleted set true
  440. s.WatcherHub.notifyWatchers(e, path, true)
  441. }
  442. s.ttlKeyHeap.pop()
  443. node.Remove(true, true, callback)
  444. s.Stats.Inc(ExpireCount)
  445. s.WatcherHub.notify(e)
  446. }
  447. }
  448. // checkDir will check whether the component is a directory under parent node.
  449. // If it is a directory, this function will return the pointer to that node.
  450. // If it does not exist, this function will create a new directory and return the pointer to that node.
  451. // If it is a file, this function will return error.
  452. func (s *store) checkDir(parent *node, dirName string) (*node, *etcdErr.Error) {
  453. node, ok := parent.Children[dirName]
  454. if ok {
  455. if node.IsDir() {
  456. return node, nil
  457. }
  458. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, node.Path, s.CurrentIndex)
  459. }
  460. n := newDir(s, path.Join(parent.Path, dirName), s.CurrentIndex+1, parent, parent.ACL, Permanent)
  461. parent.Children[dirName] = n
  462. return n, nil
  463. }
  464. // Save saves the static state of the store system.
  465. // It will not be able to save the state of watchers.
  466. // It will not save the parent field of the node. Or there will
  467. // be cyclic dependencies issue for the json package.
  468. func (s *store) Save() ([]byte, error) {
  469. s.worldLock.Lock()
  470. clonedStore := newStore()
  471. clonedStore.CurrentIndex = s.CurrentIndex
  472. clonedStore.Root = s.Root.Clone()
  473. clonedStore.WatcherHub = s.WatcherHub.clone()
  474. clonedStore.Stats = s.Stats.clone()
  475. clonedStore.CurrentVersion = s.CurrentVersion
  476. s.worldLock.Unlock()
  477. b, err := json.Marshal(clonedStore)
  478. if err != nil {
  479. return nil, err
  480. }
  481. return b, nil
  482. }
  483. // Recovery recovers the store system from a static state
  484. // It needs to recover the parent field of the nodes.
  485. // It needs to delete the expired nodes since the saved time and also
  486. // needs to create monitoring go routines.
  487. func (s *store) Recovery(state []byte) error {
  488. s.worldLock.Lock()
  489. defer s.worldLock.Unlock()
  490. err := json.Unmarshal(state, s)
  491. if err != nil {
  492. return err
  493. }
  494. s.ttlKeyHeap = newTtlKeyHeap()
  495. s.Root.recoverAndclean()
  496. return nil
  497. }
  498. func (s *store) JsonStats() []byte {
  499. s.Stats.Watchers = uint64(s.WatcherHub.count)
  500. return s.Stats.toJson()
  501. }
  502. func (s *store) TotalTransactions() uint64 {
  503. return s.Stats.TotalTranscations()
  504. }