store.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. etcdErr "github.com/coreos/etcd/error"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/jonboulle/clockwork"
  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. }
  198. return e, nil
  199. }
  200. // returns user-readable cause of failed comparison
  201. func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) string {
  202. switch which {
  203. case CompareIndexNotMatch:
  204. return fmt.Sprintf("[%v != %v]", prevIndex, n.ModifiedIndex)
  205. case CompareValueNotMatch:
  206. return fmt.Sprintf("[%v != %v]", prevValue, n.Value)
  207. default:
  208. return fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, n.Value, prevIndex, n.ModifiedIndex)
  209. }
  210. }
  211. func (s *store) CompareAndSwap(nodePath string, prevValue string, prevIndex uint64,
  212. value string, expireOpts TTLOptionSet) (*Event, error) {
  213. var err *etcdErr.Error
  214. s.worldLock.Lock()
  215. defer s.worldLock.Unlock()
  216. defer func() {
  217. if err == nil {
  218. s.Stats.Inc(CompareAndSwapSuccess)
  219. reportWriteSuccess(CompareAndSwap)
  220. return
  221. }
  222. s.Stats.Inc(CompareAndSwapFail)
  223. reportWriteFailure(CompareAndSwap)
  224. }()
  225. nodePath = path.Clean(path.Join("/", nodePath))
  226. // we do not allow the user to change "/"
  227. if s.readonlySet.Contains(nodePath) {
  228. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  229. }
  230. n, err := s.internalGet(nodePath)
  231. if err != nil {
  232. return nil, err
  233. }
  234. if n.IsDir() { // can only compare and swap file
  235. err = etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, s.CurrentIndex)
  236. return nil, err
  237. }
  238. // If both of the prevValue and prevIndex are given, we will test both of them.
  239. // Command will be executed, only if both of the tests are successful.
  240. if ok, which := n.Compare(prevValue, prevIndex); !ok {
  241. cause := getCompareFailCause(n, which, prevValue, prevIndex)
  242. err = etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  243. return nil, err
  244. }
  245. // update etcd index
  246. s.CurrentIndex++
  247. e := newEvent(CompareAndSwap, nodePath, s.CurrentIndex, n.CreatedIndex)
  248. e.EtcdIndex = s.CurrentIndex
  249. e.PrevNode = n.Repr(false, false, s.clock)
  250. eNode := e.Node
  251. // if test succeed, write the value
  252. n.Write(value, s.CurrentIndex)
  253. n.UpdateTTL(expireOpts.ExpireTime)
  254. // copy the value for safety
  255. valueCopy := value
  256. eNode.Value = &valueCopy
  257. eNode.Expiration, eNode.TTL = n.expirationAndTTL(s.clock)
  258. if !expireOpts.Refresh {
  259. s.WatcherHub.notify(e)
  260. }
  261. return e, nil
  262. }
  263. // Delete deletes the node at the given path.
  264. // If the node is a directory, recursive must be true to delete it.
  265. func (s *store) Delete(nodePath string, dir, recursive bool) (*Event, error) {
  266. var err *etcdErr.Error
  267. s.worldLock.Lock()
  268. defer s.worldLock.Unlock()
  269. defer func() {
  270. if err == nil {
  271. s.Stats.Inc(DeleteSuccess)
  272. reportWriteSuccess(Delete)
  273. return
  274. }
  275. s.Stats.Inc(DeleteFail)
  276. reportWriteFailure(Delete)
  277. }()
  278. nodePath = path.Clean(path.Join("/", nodePath))
  279. // we do not allow the user to change "/"
  280. if s.readonlySet.Contains(nodePath) {
  281. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  282. }
  283. // recursive implies dir
  284. if recursive {
  285. dir = true
  286. }
  287. n, err := s.internalGet(nodePath)
  288. if err != nil { // if the node does not exist, return error
  289. return nil, err
  290. }
  291. nextIndex := s.CurrentIndex + 1
  292. e := newEvent(Delete, nodePath, nextIndex, n.CreatedIndex)
  293. e.EtcdIndex = nextIndex
  294. e.PrevNode = n.Repr(false, false, s.clock)
  295. eNode := e.Node
  296. if n.IsDir() {
  297. eNode.Dir = true
  298. }
  299. callback := func(path string) { // notify function
  300. // notify the watchers with deleted set true
  301. s.WatcherHub.notifyWatchers(e, path, true)
  302. }
  303. err = n.Remove(dir, recursive, callback)
  304. if err != nil {
  305. return nil, err
  306. }
  307. // update etcd index
  308. s.CurrentIndex++
  309. s.WatcherHub.notify(e)
  310. return e, nil
  311. }
  312. func (s *store) CompareAndDelete(nodePath string, prevValue string, prevIndex uint64) (*Event, error) {
  313. var err *etcdErr.Error
  314. s.worldLock.Lock()
  315. defer s.worldLock.Unlock()
  316. defer func() {
  317. if err == nil {
  318. s.Stats.Inc(CompareAndDeleteSuccess)
  319. reportWriteSuccess(CompareAndDelete)
  320. return
  321. }
  322. s.Stats.Inc(CompareAndDeleteFail)
  323. reportWriteFailure(CompareAndDelete)
  324. }()
  325. nodePath = path.Clean(path.Join("/", nodePath))
  326. n, err := s.internalGet(nodePath)
  327. if err != nil { // if the node does not exist, return error
  328. return nil, err
  329. }
  330. if n.IsDir() { // can only compare and delete file
  331. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, s.CurrentIndex)
  332. }
  333. // If both of the prevValue and prevIndex are given, we will test both of them.
  334. // Command will be executed, only if both of the tests are successful.
  335. if ok, which := n.Compare(prevValue, prevIndex); !ok {
  336. cause := getCompareFailCause(n, which, prevValue, prevIndex)
  337. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  338. }
  339. // update etcd index
  340. s.CurrentIndex++
  341. e := newEvent(CompareAndDelete, nodePath, s.CurrentIndex, n.CreatedIndex)
  342. e.EtcdIndex = s.CurrentIndex
  343. e.PrevNode = n.Repr(false, false, s.clock)
  344. callback := func(path string) { // notify function
  345. // notify the watchers with deleted set true
  346. s.WatcherHub.notifyWatchers(e, path, true)
  347. }
  348. err = n.Remove(false, false, callback)
  349. if err != nil {
  350. return nil, err
  351. }
  352. s.WatcherHub.notify(e)
  353. return e, nil
  354. }
  355. func (s *store) Watch(key string, recursive, stream bool, sinceIndex uint64) (Watcher, error) {
  356. s.worldLock.RLock()
  357. defer s.worldLock.RUnlock()
  358. key = path.Clean(path.Join("/", key))
  359. if sinceIndex == 0 {
  360. sinceIndex = s.CurrentIndex + 1
  361. }
  362. // WatcherHub does not know about the current index, so we need to pass it in
  363. w, err := s.WatcherHub.watch(key, recursive, stream, sinceIndex, s.CurrentIndex)
  364. if err != nil {
  365. return nil, err
  366. }
  367. return w, nil
  368. }
  369. // walk walks all the nodePath and apply the walkFunc on each directory
  370. func (s *store) walk(nodePath string, walkFunc func(prev *node, component string) (*node, *etcdErr.Error)) (*node, *etcdErr.Error) {
  371. components := strings.Split(nodePath, "/")
  372. curr := s.Root
  373. var err *etcdErr.Error
  374. for i := 1; i < len(components); i++ {
  375. if len(components[i]) == 0 { // ignore empty string
  376. return curr, nil
  377. }
  378. curr, err = walkFunc(curr, components[i])
  379. if err != nil {
  380. return nil, err
  381. }
  382. }
  383. return curr, nil
  384. }
  385. // Update updates the value/ttl of the node.
  386. // If the node is a file, the value and the ttl can be updated.
  387. // If the node is a directory, only the ttl can be updated.
  388. func (s *store) Update(nodePath string, newValue string, expireOpts TTLOptionSet) (*Event, error) {
  389. var err *etcdErr.Error
  390. s.worldLock.Lock()
  391. defer s.worldLock.Unlock()
  392. defer func() {
  393. if err == nil {
  394. s.Stats.Inc(UpdateSuccess)
  395. reportWriteSuccess(Update)
  396. return
  397. }
  398. s.Stats.Inc(UpdateFail)
  399. reportWriteFailure(Update)
  400. }()
  401. nodePath = path.Clean(path.Join("/", nodePath))
  402. // we do not allow the user to change "/"
  403. if s.readonlySet.Contains(nodePath) {
  404. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", s.CurrentIndex)
  405. }
  406. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  407. n, err := s.internalGet(nodePath)
  408. if err != nil { // if the node does not exist, return error
  409. return nil, err
  410. }
  411. if n.IsDir() && len(newValue) != 0 {
  412. // if the node is a directory, we cannot update value to non-empty
  413. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  414. }
  415. if expireOpts.Refresh {
  416. newValue = n.Value
  417. }
  418. e := newEvent(Update, nodePath, nextIndex, n.CreatedIndex)
  419. e.EtcdIndex = nextIndex
  420. e.PrevNode = n.Repr(false, false, s.clock)
  421. eNode := e.Node
  422. n.Write(newValue, nextIndex)
  423. if n.IsDir() {
  424. eNode.Dir = true
  425. } else {
  426. // copy the value for safety
  427. newValueCopy := newValue
  428. eNode.Value = &newValueCopy
  429. }
  430. // update ttl
  431. n.UpdateTTL(expireOpts.ExpireTime)
  432. eNode.Expiration, eNode.TTL = n.expirationAndTTL(s.clock)
  433. if !expireOpts.Refresh {
  434. s.WatcherHub.notify(e)
  435. }
  436. s.CurrentIndex = nextIndex
  437. return e, nil
  438. }
  439. func (s *store) internalCreate(nodePath string, dir bool, value string, unique, replace bool,
  440. expireTime time.Time, action string) (*Event, *etcdErr.Error) {
  441. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  442. if unique { // append unique item under the node path
  443. nodePath += "/" + fmt.Sprintf("%020s", strconv.FormatUint(nextIndex, 10))
  444. }
  445. nodePath = path.Clean(path.Join("/", nodePath))
  446. // we do not allow the user to change "/"
  447. if s.readonlySet.Contains(nodePath) {
  448. return nil, etcdErr.NewError(etcdErr.EcodeRootROnly, "/", currIndex)
  449. }
  450. // Assume expire times that are way in the past are
  451. // This can occur when the time is serialized to JS
  452. if expireTime.Before(minExpireTime) {
  453. expireTime = Permanent
  454. }
  455. dirName, nodeName := path.Split(nodePath)
  456. // walk through the nodePath, create dirs and get the last directory node
  457. d, err := s.walk(dirName, s.checkDir)
  458. if err != nil {
  459. s.Stats.Inc(SetFail)
  460. reportWriteFailure(action)
  461. err.Index = currIndex
  462. return nil, err
  463. }
  464. e := newEvent(action, nodePath, nextIndex, nextIndex)
  465. eNode := e.Node
  466. n, _ := d.GetChild(nodeName)
  467. // force will try to replace an existing file
  468. if n != nil {
  469. if replace {
  470. if n.IsDir() {
  471. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  472. }
  473. e.PrevNode = n.Repr(false, false, s.clock)
  474. n.Remove(false, false, nil)
  475. } else {
  476. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, currIndex)
  477. }
  478. }
  479. if !dir { // create file
  480. // copy the value for safety
  481. valueCopy := value
  482. eNode.Value = &valueCopy
  483. n = newKV(s, nodePath, value, nextIndex, d, expireTime)
  484. } else { // create directory
  485. eNode.Dir = true
  486. n = newDir(s, nodePath, nextIndex, d, expireTime)
  487. }
  488. // we are sure d is a directory and does not have the children with name n.Name
  489. d.Add(n)
  490. // node with TTL
  491. if !n.IsPermanent() {
  492. s.ttlKeyHeap.push(n)
  493. eNode.Expiration, eNode.TTL = n.expirationAndTTL(s.clock)
  494. }
  495. s.CurrentIndex = nextIndex
  496. return e, nil
  497. }
  498. // InternalGet gets the node of the given nodePath.
  499. func (s *store) internalGet(nodePath string) (*node, *etcdErr.Error) {
  500. nodePath = path.Clean(path.Join("/", nodePath))
  501. walkFunc := func(parent *node, name string) (*node, *etcdErr.Error) {
  502. if !parent.IsDir() {
  503. err := etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path, s.CurrentIndex)
  504. return nil, err
  505. }
  506. child, ok := parent.Children[name]
  507. if ok {
  508. return child, nil
  509. }
  510. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name), s.CurrentIndex)
  511. }
  512. f, err := s.walk(nodePath, walkFunc)
  513. if err != nil {
  514. return nil, err
  515. }
  516. return f, nil
  517. }
  518. // DeleteExpiredKeys will delete all expired keys
  519. func (s *store) DeleteExpiredKeys(cutoff time.Time) {
  520. s.worldLock.Lock()
  521. defer s.worldLock.Unlock()
  522. for {
  523. node := s.ttlKeyHeap.top()
  524. if node == nil || node.ExpireTime.After(cutoff) {
  525. break
  526. }
  527. s.CurrentIndex++
  528. e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex)
  529. e.EtcdIndex = s.CurrentIndex
  530. e.PrevNode = node.Repr(false, false, s.clock)
  531. callback := func(path string) { // notify function
  532. // notify the watchers with deleted set true
  533. s.WatcherHub.notifyWatchers(e, path, true)
  534. }
  535. s.ttlKeyHeap.pop()
  536. node.Remove(true, true, callback)
  537. reportExpiredKey()
  538. s.Stats.Inc(ExpireCount)
  539. s.WatcherHub.notify(e)
  540. }
  541. }
  542. // checkDir will check whether the component is a directory under parent node.
  543. // If it is a directory, this function will return the pointer to that node.
  544. // If it does not exist, this function will create a new directory and return the pointer to that node.
  545. // If it is a file, this function will return error.
  546. func (s *store) checkDir(parent *node, dirName string) (*node, *etcdErr.Error) {
  547. node, ok := parent.Children[dirName]
  548. if ok {
  549. if node.IsDir() {
  550. return node, nil
  551. }
  552. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, node.Path, s.CurrentIndex)
  553. }
  554. n := newDir(s, path.Join(parent.Path, dirName), s.CurrentIndex+1, parent, Permanent)
  555. parent.Children[dirName] = n
  556. return n, nil
  557. }
  558. // Save saves the static state of the store system.
  559. // It will not be able to save the state of watchers.
  560. // It will not save the parent field of the node. Or there will
  561. // be cyclic dependencies issue for the json package.
  562. func (s *store) Save() ([]byte, error) {
  563. b, err := json.Marshal(s.Clone())
  564. if err != nil {
  565. return nil, err
  566. }
  567. return b, nil
  568. }
  569. func (s *store) SaveNoCopy() ([]byte, error) {
  570. b, err := json.Marshal(s)
  571. if err != nil {
  572. return nil, err
  573. }
  574. return b, nil
  575. }
  576. func (s *store) Clone() Store {
  577. s.worldLock.Lock()
  578. clonedStore := newStore()
  579. clonedStore.CurrentIndex = s.CurrentIndex
  580. clonedStore.Root = s.Root.Clone()
  581. clonedStore.WatcherHub = s.WatcherHub.clone()
  582. clonedStore.Stats = s.Stats.clone()
  583. clonedStore.CurrentVersion = s.CurrentVersion
  584. s.worldLock.Unlock()
  585. return clonedStore
  586. }
  587. // Recovery recovers the store system from a static state
  588. // It needs to recover the parent field of the nodes.
  589. // It needs to delete the expired nodes since the saved time and also
  590. // needs to create monitoring go routines.
  591. func (s *store) Recovery(state []byte) error {
  592. s.worldLock.Lock()
  593. defer s.worldLock.Unlock()
  594. err := json.Unmarshal(state, s)
  595. if err != nil {
  596. return err
  597. }
  598. s.ttlKeyHeap = newTtlKeyHeap()
  599. s.Root.recoverAndclean()
  600. return nil
  601. }
  602. func (s *store) JsonStats() []byte {
  603. s.Stats.Watchers = uint64(s.WatcherHub.count)
  604. return s.Stats.toJson()
  605. }