store.go 19 KB

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