store.go 19 KB

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