store.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package store
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. etcdErr "github.com/coreos/etcd/error"
  11. )
  12. type Store struct {
  13. Root *Node
  14. WatcherHub *watcherHub
  15. Index uint64
  16. Term uint64
  17. Stats *Stats
  18. worldLock sync.RWMutex // stop the world lock. Used to do snapshot
  19. }
  20. func New() *Store {
  21. s := new(Store)
  22. s.Root = newDir("/", 0, 0, nil, "", Permanent)
  23. s.Stats = newStats()
  24. s.WatcherHub = newWatchHub(1000)
  25. return s
  26. }
  27. func (s *Store) Get(nodePath string, recursive, sorted bool, index uint64, term uint64) (*Event, error) {
  28. s.worldLock.RLock()
  29. defer s.worldLock.RUnlock()
  30. nodePath = path.Clean(path.Join("/", nodePath))
  31. n, err := s.internalGet(nodePath, index, term)
  32. if err != nil {
  33. s.Stats.Inc(GetFail)
  34. return nil, err
  35. }
  36. e := newEvent(Get, nodePath, index, term)
  37. if n.IsDir() { // node is dir
  38. e.Dir = true
  39. children, _ := n.List()
  40. e.KVPairs = make([]KeyValuePair, len(children))
  41. // we do not use the index in the children slice directly
  42. // we need to skip the hidden one
  43. i := 0
  44. for _, child := range children {
  45. if child.IsHidden() { // get will not list hidden node
  46. continue
  47. }
  48. e.KVPairs[i] = child.Pair(recursive, sorted)
  49. i++
  50. }
  51. // eliminate hidden nodes
  52. e.KVPairs = e.KVPairs[:i]
  53. rootPairs := KeyValuePair{
  54. KVPairs: e.KVPairs,
  55. }
  56. if sorted {
  57. sort.Sort(rootPairs)
  58. }
  59. } else { // node is file
  60. e.Value = n.Value
  61. }
  62. if n.ExpireTime.Sub(Permanent) != 0 {
  63. e.Expiration = &n.ExpireTime
  64. e.TTL = int64(n.ExpireTime.Sub(time.Now())/time.Second) + 1
  65. }
  66. s.Stats.Inc(GetSuccess)
  67. return e, nil
  68. }
  69. // Create function creates the Node at nodePath. Create will help to create intermediate directories with no ttl.
  70. // If the node has already existed, create will fail.
  71. // If any node on the path is a file, create will fail.
  72. func (s *Store) Create(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  73. s.worldLock.RLock()
  74. defer s.worldLock.RUnlock()
  75. nodePath = path.Clean(path.Join("/", nodePath))
  76. // make sure we can create the node
  77. _, err := s.internalGet(nodePath, index, term)
  78. if err == nil { // key already exists
  79. s.Stats.Inc(SetFail)
  80. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath)
  81. }
  82. etcdError, _ := err.(etcdErr.Error)
  83. if etcdError.ErrorCode == 104 { // we cannot create the key due to meet a file while walking
  84. s.Stats.Inc(SetFail)
  85. return nil, err
  86. }
  87. dir, _ := path.Split(nodePath)
  88. // walk through the nodePath, create dirs and get the last directory node
  89. d, err := s.walk(dir, s.checkDir)
  90. if err != nil {
  91. s.Stats.Inc(SetFail)
  92. return nil, err
  93. }
  94. e := newEvent(Create, nodePath, s.Index, s.Term)
  95. var n *Node
  96. if len(value) != 0 { // create file
  97. e.Value = value
  98. n = newFile(nodePath, value, s.Index, s.Term, d, "", expireTime)
  99. } else { // create directory
  100. e.Dir = true
  101. n = newDir(nodePath, s.Index, s.Term, d, "", expireTime)
  102. }
  103. err = d.Add(n)
  104. if err != nil {
  105. s.Stats.Inc(SetFail)
  106. return nil, err
  107. }
  108. // Node with TTL
  109. if expireTime.Sub(Permanent) != 0 {
  110. n.Expire(s)
  111. e.Expiration = &n.ExpireTime
  112. e.TTL = int64(expireTime.Sub(time.Now())/time.Second) + 1
  113. }
  114. s.WatcherHub.notify(e)
  115. s.Stats.Inc(SetSuccess)
  116. return e, nil
  117. }
  118. // Update function updates the value/ttl of the node.
  119. // If the node is a file, the value and the ttl can be updated.
  120. // If the node is a directory, only the ttl can be updated.
  121. func (s *Store) Update(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  122. s.worldLock.RLock()
  123. defer s.worldLock.RUnlock()
  124. n, err := s.internalGet(nodePath, index, term)
  125. if err != nil { // if the node does not exist, return error
  126. s.Stats.Inc(UpdateFail)
  127. return nil, err
  128. }
  129. e := newEvent(Update, nodePath, s.Index, s.Term)
  130. if n.IsDir() { // if the node is a directory, we can only update ttl
  131. if len(value) != 0 {
  132. s.Stats.Inc(UpdateFail)
  133. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)
  134. }
  135. } else { // if the node is a file, we can update value and ttl
  136. e.PrevValue = n.Value
  137. if len(value) != 0 {
  138. e.Value = value
  139. }
  140. n.Write(value, index, term)
  141. }
  142. // update ttl
  143. n.UpdateTTL(expireTime, s)
  144. e.Expiration = &n.ExpireTime
  145. e.TTL = int64(expireTime.Sub(time.Now())/time.Second) + 1
  146. s.WatcherHub.notify(e)
  147. s.Stats.Inc(UpdateSuccess)
  148. return e, nil
  149. }
  150. func (s *Store) TestAndSet(nodePath string, prevValue string, prevIndex uint64,
  151. value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  152. s.worldLock.RLock()
  153. defer s.worldLock.RUnlock()
  154. n, err := s.internalGet(nodePath, index, term)
  155. if err != nil {
  156. s.Stats.Inc(TestAndSetFail)
  157. return nil, err
  158. }
  159. if n.IsDir() { // can only test and set file
  160. s.Stats.Inc(TestAndSetFail)
  161. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)
  162. }
  163. if n.Value == prevValue || n.ModifiedIndex == prevIndex {
  164. // if test succeed, write the value
  165. e := newEvent(TestAndSet, nodePath, index, term)
  166. e.PrevValue = n.Value
  167. e.Value = value
  168. n.Write(value, index, term)
  169. n.UpdateTTL(expireTime, s)
  170. s.WatcherHub.notify(e)
  171. s.Stats.Inc(TestAndSetSuccess)
  172. return e, nil
  173. }
  174. cause := fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, n.Value, prevIndex, n.ModifiedIndex)
  175. s.Stats.Inc(TestAndSetFail)
  176. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause)
  177. }
  178. // Delete function deletes the node at the given path.
  179. // If the node is a directory, recursive must be true to delete it.
  180. func (s *Store) Delete(nodePath string, recursive bool, index uint64, term uint64) (*Event, error) {
  181. s.worldLock.RLock()
  182. defer s.worldLock.RUnlock()
  183. n, err := s.internalGet(nodePath, index, term)
  184. if err != nil { // if the node does not exist, return error
  185. s.Stats.Inc(DeleteFail)
  186. return nil, err
  187. }
  188. e := newEvent(Delete, nodePath, index, term)
  189. if n.IsDir() {
  190. e.Dir = true
  191. } else {
  192. e.PrevValue = n.Value
  193. }
  194. callback := func(path string) { // notify function
  195. s.WatcherHub.notifyWithPath(e, path, true)
  196. }
  197. err = n.Remove(recursive, callback)
  198. if err != nil {
  199. s.Stats.Inc(DeleteFail)
  200. return nil, err
  201. }
  202. s.WatcherHub.notify(e)
  203. s.Stats.Inc(DeleteSuccess)
  204. return e, nil
  205. }
  206. func (s *Store) Watch(prefix string, recursive bool, sinceIndex uint64, index uint64, term uint64) (<-chan *Event, error) {
  207. s.worldLock.RLock()
  208. defer s.worldLock.RUnlock()
  209. s.Index, s.Term = index, term
  210. if sinceIndex == 0 {
  211. return s.WatcherHub.watch(prefix, recursive, index+1)
  212. }
  213. return s.WatcherHub.watch(prefix, recursive, sinceIndex)
  214. }
  215. // walk function walks all the nodePath and apply the walkFunc on each directory
  216. func (s *Store) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, error)) (*Node, error) {
  217. components := strings.Split(nodePath, "/")
  218. curr := s.Root
  219. var err error
  220. for i := 1; i < len(components); i++ {
  221. if len(components[i]) == 0 { // ignore empty string
  222. return curr, nil
  223. }
  224. curr, err = walkFunc(curr, components[i])
  225. if err != nil {
  226. return nil, err
  227. }
  228. }
  229. return curr, nil
  230. }
  231. // InternalGet function get the node of the given nodePath.
  232. func (s *Store) internalGet(nodePath string, index uint64, term uint64) (*Node, error) {
  233. nodePath = path.Clean(path.Join("/", nodePath))
  234. // update file system known index and term
  235. s.Index, s.Term = index, term
  236. walkFunc := func(parent *Node, name string) (*Node, error) {
  237. if !parent.IsDir() {
  238. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path)
  239. }
  240. child, ok := parent.Children[name]
  241. if ok {
  242. return child, nil
  243. }
  244. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name))
  245. }
  246. f, err := s.walk(nodePath, walkFunc)
  247. if err != nil {
  248. return nil, err
  249. }
  250. return f, nil
  251. }
  252. // checkDir function will check whether the component is a directory under parent node.
  253. // If it is a directory, this function will return the pointer to that node.
  254. // If it does not exist, this function will create a new directory and return the pointer to that node.
  255. // If it is a file, this function will return error.
  256. func (s *Store) checkDir(parent *Node, dirName string) (*Node, error) {
  257. subDir, ok := parent.Children[dirName]
  258. if ok {
  259. return subDir, nil
  260. }
  261. n := newDir(path.Join(parent.Path, dirName), s.Index, s.Term, parent, parent.ACL, Permanent)
  262. parent.Children[dirName] = n
  263. return n, nil
  264. }
  265. // Save function saves the static state of the store system.
  266. // Save function will not be able to save the state of watchers.
  267. // Save function will not save the parent field of the node. Or there will
  268. // be cyclic dependencies issue for the json package.
  269. func (s *Store) Save() ([]byte, error) {
  270. s.worldLock.Lock()
  271. clonedStore := New()
  272. clonedStore.Index = s.Index
  273. clonedStore.Term = s.Term
  274. clonedStore.Root = s.Root.Clone()
  275. clonedStore.WatcherHub = s.WatcherHub.clone()
  276. clonedStore.Stats = s.Stats.clone()
  277. s.worldLock.Unlock()
  278. b, err := json.Marshal(clonedStore)
  279. if err != nil {
  280. return nil, err
  281. }
  282. return b, nil
  283. }
  284. // recovery function recovery the store system from a static state.
  285. // It needs to recovery the parent field of the nodes.
  286. // It needs to delete the expired nodes since the saved time and also
  287. // need to create monitor go routines.
  288. func (s *Store) Recovery(state []byte) error {
  289. s.worldLock.Lock()
  290. defer s.worldLock.Unlock()
  291. err := json.Unmarshal(state, s)
  292. if err != nil {
  293. return err
  294. }
  295. s.Root.recoverAndclean(s)
  296. return nil
  297. }
  298. func (s *Store) JsonStats() []byte {
  299. s.Stats.Watchers = uint64(s.WatcherHub.count)
  300. return s.Stats.toJson()
  301. }