store.go 11 KB

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