store.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. }
  185. return c, err
  186. }
  187. // walk function walks all the nodePath and apply the walkFunc on each directory
  188. func (s *Store) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, *etcdErr.Error)) (*Node, *etcdErr.Error) {
  189. components := strings.Split(nodePath, "/")
  190. curr := s.Root
  191. var err *etcdErr.Error
  192. for i := 1; i < len(components); i++ {
  193. if len(components[i]) == 0 { // ignore empty string
  194. return curr, nil
  195. }
  196. curr, err = walkFunc(curr, components[i])
  197. if err != nil {
  198. return nil, err
  199. }
  200. }
  201. return curr, nil
  202. }
  203. func (s *Store) internalCreate(nodePath string, value string, incrementalSuffix bool, force bool,
  204. expireTime time.Time, index uint64, term uint64, action string) (*Event, error) {
  205. if incrementalSuffix { // append unique incremental suffix to the node path
  206. nodePath += "_" + strconv.FormatUint(index, 10)
  207. }
  208. nodePath = path.Clean(path.Join("/", nodePath))
  209. // make sure we can create the node
  210. _, err := s.internalGet(nodePath, index, term)
  211. if err == nil && !force { // key already exists
  212. s.Stats.Inc(SetFail)
  213. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath, index, term)
  214. }
  215. if err != nil && err.ErrorCode == 104 { // we cannot create the key due to meet a file while walking
  216. s.Stats.Inc(SetFail)
  217. return nil, err
  218. }
  219. dir, newNodeName := path.Split(nodePath)
  220. // walk through the nodePath, create dirs and get the last directory node
  221. d, err := s.walk(dir, s.checkDir)
  222. if err != nil {
  223. s.Stats.Inc(SetFail)
  224. return nil, err
  225. }
  226. e := newEvent(action, nodePath, s.Index, s.Term)
  227. if force { // force will try to replace a existing file
  228. n, _ := d.GetChild(newNodeName)
  229. if n != nil {
  230. if n.IsDir() {
  231. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath, index, term)
  232. }
  233. e.PrevValue, _ = n.Read()
  234. n.Remove(false, nil)
  235. }
  236. }
  237. var n *Node
  238. if len(value) != 0 { // create file
  239. e.Value = value
  240. n = newKV(nodePath, value, s.Index, s.Term, d, "", expireTime)
  241. } else { // create directory
  242. e.Dir = true
  243. n = newDir(nodePath, s.Index, s.Term, d, "", expireTime)
  244. }
  245. err = d.Add(n)
  246. if err != nil {
  247. s.Stats.Inc(SetFail)
  248. return nil, err
  249. }
  250. // Node with TTL
  251. if expireTime.Sub(Permanent) != 0 {
  252. n.Expire(s)
  253. e.Expiration, e.TTL = n.ExpirationAndTTL()
  254. }
  255. s.WatcherHub.notify(e)
  256. s.Stats.Inc(SetSuccess)
  257. return e, nil
  258. }
  259. // InternalGet function get the node of the given nodePath.
  260. func (s *Store) internalGet(nodePath string, index uint64, term uint64) (*Node, *etcdErr.Error) {
  261. nodePath = path.Clean(path.Join("/", nodePath))
  262. // update file system known index and term
  263. if index > s.Index {
  264. s.Index, s.Term = index, term
  265. }
  266. walkFunc := func(parent *Node, name string) (*Node, *etcdErr.Error) {
  267. if !parent.IsDir() {
  268. err := etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path, index, term)
  269. return nil, err
  270. }
  271. child, ok := parent.Children[name]
  272. if ok {
  273. return child, nil
  274. }
  275. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name), index, term)
  276. }
  277. f, err := s.walk(nodePath, walkFunc)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return f, nil
  282. }
  283. // checkDir function will check whether the component is a directory under parent node.
  284. // If it is a directory, this function will return the pointer to that node.
  285. // If it does not exist, this function will create a new directory and return the pointer to that node.
  286. // If it is a file, this function will return error.
  287. func (s *Store) checkDir(parent *Node, dirName string) (*Node, *etcdErr.Error) {
  288. subDir, ok := parent.Children[dirName]
  289. if ok {
  290. return subDir, nil
  291. }
  292. n := newDir(path.Join(parent.Path, dirName), s.Index, s.Term, parent, parent.ACL, Permanent)
  293. parent.Children[dirName] = n
  294. return n, nil
  295. }
  296. // Save function saves the static state of the store system.
  297. // Save function will not be able to save the state of watchers.
  298. // Save function will not save the parent field of the node. Or there will
  299. // be cyclic dependencies issue for the json package.
  300. func (s *Store) Save() ([]byte, error) {
  301. s.worldLock.Lock()
  302. clonedStore := New()
  303. clonedStore.Index = s.Index
  304. clonedStore.Term = s.Term
  305. clonedStore.Root = s.Root.Clone()
  306. clonedStore.WatcherHub = s.WatcherHub.clone()
  307. clonedStore.Stats = s.Stats.clone()
  308. s.worldLock.Unlock()
  309. b, err := json.Marshal(clonedStore)
  310. if err != nil {
  311. return nil, err
  312. }
  313. return b, nil
  314. }
  315. // recovery function recovery the store system from a static state.
  316. // It needs to recovery the parent field of the nodes.
  317. // It needs to delete the expired nodes since the saved time and also
  318. // need to create monitor go routines.
  319. func (s *Store) Recovery(state []byte) error {
  320. s.worldLock.Lock()
  321. defer s.worldLock.Unlock()
  322. err := json.Unmarshal(state, s)
  323. if err != nil {
  324. return err
  325. }
  326. s.Root.recoverAndclean(s)
  327. return nil
  328. }
  329. func (s *Store) JsonStats() []byte {
  330. s.Stats.Watchers = uint64(s.WatcherHub.count)
  331. return s.Stats.toJson()
  332. }