store.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. "sort"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. etcdErr "github.com/coreos/etcd/error"
  24. )
  25. // The default version to set when the store is first initialized.
  26. const defaultVersion = 2
  27. var minExpireTime time.Time
  28. func init() {
  29. minExpireTime, _ = time.Parse(time.RFC3339, "2000-01-01T00:00:00Z")
  30. }
  31. type Store interface {
  32. Version() int
  33. CommandFactory() CommandFactory
  34. Index() uint64
  35. Get(nodePath string, recursive, sorted bool) (*Event, error)
  36. Set(nodePath string, value string, expireTime time.Time) (*Event, error)
  37. Update(nodePath string, newValue string, expireTime time.Time) (*Event, error)
  38. Create(nodePath string, value string, incrementalSuffix bool,
  39. expireTime time.Time) (*Event, error)
  40. CompareAndSwap(nodePath string, prevValue string, prevIndex uint64,
  41. value string, expireTime time.Time) (*Event, error)
  42. Delete(nodePath string, recursive bool) (*Event, error)
  43. Watch(prefix string, recursive bool, sinceIndex uint64) (<-chan *Event, error)
  44. Save() ([]byte, error)
  45. Recovery(state []byte) error
  46. TotalTransactions() uint64
  47. JsonStats() []byte
  48. DeleteExpiredKeys(cutoff time.Time)
  49. }
  50. type store struct {
  51. Root *Node
  52. WatcherHub *watcherHub
  53. CurrentIndex uint64
  54. Stats *Stats
  55. CurrentVersion int
  56. ttlKeyHeap *ttlKeyHeap // need to recovery manually
  57. worldLock sync.RWMutex // stop the world lock
  58. }
  59. func New() Store {
  60. return newStore()
  61. }
  62. func newStore() *store {
  63. s := new(store)
  64. s.CurrentVersion = defaultVersion
  65. s.Root = newDir(s, "/", s.CurrentIndex, nil, "", Permanent)
  66. s.Stats = newStats()
  67. s.WatcherHub = newWatchHub(1000)
  68. s.ttlKeyHeap = newTtlKeyHeap()
  69. return s
  70. }
  71. // Version retrieves current version of the store.
  72. func (s *store) Version() int {
  73. return s.CurrentVersion
  74. }
  75. // Retrieves current of the store
  76. func (s *store) Index() uint64 {
  77. return s.CurrentIndex
  78. }
  79. // CommandFactory retrieves the command factory for the current version of the store.
  80. func (s *store) CommandFactory() CommandFactory {
  81. return GetCommandFactory(s.Version())
  82. }
  83. // Get function returns a get event.
  84. // If recursive is true, it will return all the content under the node path.
  85. // If sorted is true, it will sort the content by keys.
  86. func (s *store) Get(nodePath string, recursive, sorted bool) (*Event, error) {
  87. s.worldLock.RLock()
  88. defer s.worldLock.RUnlock()
  89. nodePath = path.Clean(path.Join("/", nodePath))
  90. n, err := s.internalGet(nodePath)
  91. if err != nil {
  92. s.Stats.Inc(GetFail)
  93. return nil, err
  94. }
  95. e := newEvent(Get, nodePath, n.ModifiedIndex)
  96. if n.IsDir() { // node is a directory
  97. e.Dir = true
  98. children, _ := n.List()
  99. e.KVPairs = make([]KeyValuePair, len(children))
  100. // we do not use the index in the children slice directly
  101. // we need to skip the hidden one
  102. i := 0
  103. for _, child := range children {
  104. if child.IsHidden() { // get will not return hidden nodes
  105. continue
  106. }
  107. e.KVPairs[i] = child.Pair(recursive, sorted)
  108. i++
  109. }
  110. // eliminate hidden nodes
  111. e.KVPairs = e.KVPairs[:i]
  112. if sorted {
  113. sort.Sort(e.KVPairs)
  114. }
  115. } else { // node is a file
  116. e.Value, _ = n.Read()
  117. }
  118. e.Expiration, e.TTL = n.ExpirationAndTTL()
  119. s.Stats.Inc(GetSuccess)
  120. return e, nil
  121. }
  122. // Create function creates the Node at nodePath. Create will help to create intermediate directories with no ttl.
  123. // If the node has already existed, create will fail.
  124. // If any node on the path is a file, create will fail.
  125. func (s *store) Create(nodePath string, value string, unique bool, expireTime time.Time) (*Event, error) {
  126. nodePath = path.Clean(path.Join("/", nodePath))
  127. s.worldLock.Lock()
  128. defer s.worldLock.Unlock()
  129. e, err := s.internalCreate(nodePath, value, unique, false, expireTime, Create)
  130. if err == nil {
  131. s.Stats.Inc(CreateSuccess)
  132. } else {
  133. s.Stats.Inc(CreateFail)
  134. }
  135. return e, err
  136. }
  137. // Set function creates or replace the Node at nodePath.
  138. func (s *store) Set(nodePath string, value string, expireTime time.Time) (*Event, error) {
  139. nodePath = path.Clean(path.Join("/", nodePath))
  140. s.worldLock.Lock()
  141. defer s.worldLock.Unlock()
  142. e, err := s.internalCreate(nodePath, value, false, true, expireTime, Set)
  143. if err == nil {
  144. s.Stats.Inc(SetSuccess)
  145. } else {
  146. s.Stats.Inc(SetFail)
  147. }
  148. return e, err
  149. }
  150. func (s *store) CompareAndSwap(nodePath string, prevValue string, prevIndex uint64,
  151. value string, expireTime time.Time) (*Event, error) {
  152. nodePath = path.Clean(path.Join("/", nodePath))
  153. s.worldLock.Lock()
  154. defer s.worldLock.Unlock()
  155. n, err := s.internalGet(nodePath)
  156. if err != nil {
  157. s.Stats.Inc(CompareAndSwapFail)
  158. return nil, err
  159. }
  160. if n.IsDir() { // can only test and set file
  161. s.Stats.Inc(CompareAndSwapFail)
  162. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, s.CurrentIndex)
  163. }
  164. // If both of the prevValue and prevIndex are given, we will test both of them.
  165. // Command will be executed, only if both of the tests are successful.
  166. if (prevValue == "" || n.Value == prevValue) && (prevIndex == 0 || n.ModifiedIndex == prevIndex) {
  167. // update etcd index
  168. s.CurrentIndex++
  169. e := newEvent(CompareAndSwap, nodePath, s.CurrentIndex)
  170. e.PrevValue = n.Value
  171. // if test succeed, write the value
  172. n.Write(value, s.CurrentIndex)
  173. n.UpdateTTL(expireTime)
  174. e.Value = value
  175. e.Expiration, e.TTL = n.ExpirationAndTTL()
  176. s.WatcherHub.notify(e)
  177. s.Stats.Inc(CompareAndSwapSuccess)
  178. return e, nil
  179. }
  180. cause := fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, n.Value, prevIndex, n.ModifiedIndex)
  181. s.Stats.Inc(CompareAndSwapFail)
  182. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause, s.CurrentIndex)
  183. }
  184. // Delete function deletes the node at the given path.
  185. // If the node is a directory, recursive must be true to delete it.
  186. func (s *store) Delete(nodePath string, recursive bool) (*Event, error) {
  187. nodePath = path.Clean(path.Join("/", nodePath))
  188. s.worldLock.Lock()
  189. defer s.worldLock.Unlock()
  190. nextIndex := s.CurrentIndex + 1
  191. n, err := s.internalGet(nodePath)
  192. if err != nil { // if the node does not exist, return error
  193. s.Stats.Inc(DeleteFail)
  194. return nil, err
  195. }
  196. e := newEvent(Delete, nodePath, nextIndex)
  197. if n.IsDir() {
  198. e.Dir = true
  199. } else {
  200. e.PrevValue = n.Value
  201. }
  202. callback := func(path string) { // notify function
  203. // notify the watchers with delted set true
  204. s.WatcherHub.notifyWatchers(e, path, true)
  205. }
  206. err = n.Remove(recursive, callback)
  207. if err != nil {
  208. s.Stats.Inc(DeleteFail)
  209. return nil, err
  210. }
  211. // update etcd index
  212. s.CurrentIndex++
  213. s.WatcherHub.notify(e)
  214. s.Stats.Inc(DeleteSuccess)
  215. return e, nil
  216. }
  217. func (s *store) Watch(prefix string, recursive bool, sinceIndex uint64) (<-chan *Event, error) {
  218. prefix = path.Clean(path.Join("/", prefix))
  219. nextIndex := s.CurrentIndex + 1
  220. s.worldLock.RLock()
  221. defer s.worldLock.RUnlock()
  222. var c <-chan *Event
  223. var err *etcdErr.Error
  224. if sinceIndex == 0 {
  225. c, err = s.WatcherHub.watch(prefix, recursive, nextIndex)
  226. } else {
  227. c, err = s.WatcherHub.watch(prefix, recursive, sinceIndex)
  228. }
  229. if err != nil {
  230. // watchhub do not know the current Index
  231. // we need to attach the currentIndex here
  232. err.Index = s.CurrentIndex
  233. return nil, err
  234. }
  235. return c, nil
  236. }
  237. // walk function walks all the nodePath and apply the walkFunc on each directory
  238. func (s *store) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, *etcdErr.Error)) (*Node, *etcdErr.Error) {
  239. components := strings.Split(nodePath, "/")
  240. curr := s.Root
  241. var err *etcdErr.Error
  242. for i := 1; i < len(components); i++ {
  243. if len(components[i]) == 0 { // ignore empty string
  244. return curr, nil
  245. }
  246. curr, err = walkFunc(curr, components[i])
  247. if err != nil {
  248. return nil, err
  249. }
  250. }
  251. return curr, nil
  252. }
  253. // Update function updates the value/ttl of the node.
  254. // If the node is a file, the value and the ttl can be updated.
  255. // If the node is a directory, only the ttl can be updated.
  256. func (s *store) Update(nodePath string, newValue string, expireTime time.Time) (*Event, error) {
  257. s.worldLock.Lock()
  258. defer s.worldLock.Unlock()
  259. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  260. nodePath = path.Clean(path.Join("/", nodePath))
  261. n, err := s.internalGet(nodePath)
  262. if err != nil { // if the node does not exist, return error
  263. s.Stats.Inc(UpdateFail)
  264. return nil, err
  265. }
  266. e := newEvent(Update, nodePath, nextIndex)
  267. if len(newValue) != 0 {
  268. if n.IsDir() {
  269. // if the node is a directory, we cannot update value
  270. s.Stats.Inc(UpdateFail)
  271. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  272. }
  273. e.PrevValue = n.Value
  274. n.Write(newValue, nextIndex)
  275. e.Value = newValue
  276. } else {
  277. // do not update value
  278. e.Value = n.Value
  279. }
  280. // update ttl
  281. n.UpdateTTL(expireTime)
  282. e.Expiration, e.TTL = n.ExpirationAndTTL()
  283. s.WatcherHub.notify(e)
  284. s.Stats.Inc(UpdateSuccess)
  285. s.CurrentIndex = nextIndex
  286. return e, nil
  287. }
  288. func (s *store) internalCreate(nodePath string, value string, unique bool, replace bool,
  289. expireTime time.Time, action string) (*Event, error) {
  290. currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1
  291. if unique { // append unique item under the node path
  292. nodePath += "/" + strconv.FormatUint(nextIndex, 10)
  293. }
  294. nodePath = path.Clean(path.Join("/", nodePath))
  295. // Assume expire times that are way in the past are not valid.
  296. // This can occur when the time is serialized to JSON and read back in.
  297. if expireTime.Before(minExpireTime) {
  298. expireTime = Permanent
  299. }
  300. dir, newNodeName := path.Split(nodePath)
  301. // walk through the nodePath, create dirs and get the last directory node
  302. d, err := s.walk(dir, s.checkDir)
  303. if err != nil {
  304. s.Stats.Inc(SetFail)
  305. err.Index = currIndex
  306. return nil, err
  307. }
  308. e := newEvent(action, nodePath, nextIndex)
  309. n, _ := d.GetChild(newNodeName)
  310. // force will try to replace a existing file
  311. if n != nil {
  312. if replace {
  313. if n.IsDir() {
  314. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, currIndex)
  315. }
  316. e.PrevValue, _ = n.Read()
  317. n.Remove(false, nil)
  318. } else {
  319. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, currIndex)
  320. }
  321. }
  322. if len(value) != 0 { // create file
  323. e.Value = value
  324. n = newKV(s, nodePath, value, nextIndex, d, "", expireTime)
  325. } else { // create directory
  326. e.Dir = true
  327. n = newDir(s, nodePath, nextIndex, d, "", expireTime)
  328. }
  329. // we are sure d is a directory and does not have the children with name n.Name
  330. d.Add(n)
  331. // Node with TTL
  332. if !n.IsPermanent() {
  333. s.ttlKeyHeap.push(n)
  334. e.Expiration, e.TTL = n.ExpirationAndTTL()
  335. }
  336. s.CurrentIndex = nextIndex
  337. s.WatcherHub.notify(e)
  338. return e, nil
  339. }
  340. // InternalGet function get the node of the given nodePath.
  341. func (s *store) internalGet(nodePath string) (*Node, *etcdErr.Error) {
  342. nodePath = path.Clean(path.Join("/", nodePath))
  343. walkFunc := func(parent *Node, name string) (*Node, *etcdErr.Error) {
  344. if !parent.IsDir() {
  345. err := etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path, s.CurrentIndex)
  346. return nil, err
  347. }
  348. child, ok := parent.Children[name]
  349. if ok {
  350. return child, nil
  351. }
  352. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name), s.CurrentIndex)
  353. }
  354. f, err := s.walk(nodePath, walkFunc)
  355. if err != nil {
  356. return nil, err
  357. }
  358. return f, nil
  359. }
  360. // deleteExpiredKyes will delete all
  361. func (s *store) DeleteExpiredKeys(cutoff time.Time) {
  362. s.worldLock.Lock()
  363. defer s.worldLock.Unlock()
  364. for {
  365. node := s.ttlKeyHeap.top()
  366. if node == nil || node.ExpireTime.After(cutoff) {
  367. break
  368. }
  369. s.ttlKeyHeap.pop()
  370. node.Remove(true, nil)
  371. s.CurrentIndex++
  372. s.Stats.Inc(ExpireCount)
  373. s.WatcherHub.notify(newEvent(Expire, node.Path, s.CurrentIndex))
  374. }
  375. }
  376. // checkDir function will check whether the component is a directory under parent node.
  377. // If it is a directory, this function will return the pointer to that node.
  378. // If it does not exist, this function will create a new directory and return the pointer to that node.
  379. // If it is a file, this function will return error.
  380. func (s *store) checkDir(parent *Node, dirName string) (*Node, *etcdErr.Error) {
  381. node, ok := parent.Children[dirName]
  382. if ok {
  383. if node.IsDir() {
  384. return node, nil
  385. }
  386. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path, s.CurrentIndex)
  387. }
  388. n := newDir(s, path.Join(parent.Path, dirName), s.CurrentIndex+1, parent, parent.ACL, Permanent)
  389. parent.Children[dirName] = n
  390. return n, nil
  391. }
  392. // Save function saves the static state of the store system.
  393. // Save function will not be able to save the state of watchers.
  394. // Save function will not save the parent field of the node. Or there will
  395. // be cyclic dependencies issue for the json package.
  396. func (s *store) Save() ([]byte, error) {
  397. s.worldLock.Lock()
  398. clonedStore := newStore()
  399. clonedStore.CurrentIndex = s.CurrentIndex
  400. clonedStore.Root = s.Root.Clone()
  401. clonedStore.WatcherHub = s.WatcherHub.clone()
  402. clonedStore.Stats = s.Stats.clone()
  403. clonedStore.CurrentVersion = s.CurrentVersion
  404. s.worldLock.Unlock()
  405. b, err := json.Marshal(clonedStore)
  406. if err != nil {
  407. return nil, err
  408. }
  409. return b, nil
  410. }
  411. // recovery function recovery the store system from a static state.
  412. // It needs to recovery the parent field of the nodes.
  413. // It needs to delete the expired nodes since the saved time and also
  414. // need to create monitor go routines.
  415. func (s *store) Recovery(state []byte) error {
  416. s.worldLock.Lock()
  417. defer s.worldLock.Unlock()
  418. err := json.Unmarshal(state, s)
  419. if err != nil {
  420. return err
  421. }
  422. s.ttlKeyHeap = newTtlKeyHeap()
  423. s.Root.recoverAndclean()
  424. return nil
  425. }
  426. func (s *store) JsonStats() []byte {
  427. s.Stats.Watchers = uint64(s.WatcherHub.count)
  428. return s.Stats.toJson()
  429. }
  430. func (s *store) TotalTransactions() uint64 {
  431. return s.Stats.TotalTranscations()
  432. }