node.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package store
  2. import (
  3. "path"
  4. "sort"
  5. "sync"
  6. "time"
  7. etcdErr "github.com/coreos/etcd/error"
  8. )
  9. var (
  10. Permanent time.Time
  11. )
  12. const (
  13. normal = iota
  14. removed
  15. )
  16. // Node is the basic element in the store system.
  17. // A key-value pair will have a string value
  18. // A directory will have a children map
  19. type Node struct {
  20. Path string
  21. CreateIndex uint64
  22. CreateTerm uint64
  23. ModifiedIndex uint64
  24. ModifiedTerm uint64
  25. Parent *Node `json:"-"` // should not encode this field! avoid cyclical dependency.
  26. ExpireTime time.Time
  27. ACL string
  28. Value string // for key-value pair
  29. Children map[string]*Node // for directory
  30. // a ttl node will have an expire routine associated with it.
  31. // we need a channel to stop that routine when the expiration changes.
  32. stopExpire chan bool
  33. // ensure we only delete the node once
  34. // expire and remove may try to delete a node twice
  35. once sync.Once
  36. }
  37. // newKV creates a Key-Value pair
  38. func newKV(nodePath string, value string, createIndex uint64,
  39. createTerm uint64, parent *Node, ACL string, expireTime time.Time) *Node {
  40. return &Node{
  41. Path: nodePath,
  42. CreateIndex: createIndex,
  43. CreateTerm: createTerm,
  44. ModifiedIndex: createIndex,
  45. ModifiedTerm: createTerm,
  46. Parent: parent,
  47. ACL: ACL,
  48. stopExpire: make(chan bool, 1),
  49. ExpireTime: expireTime,
  50. Value: value,
  51. }
  52. }
  53. // newDir creates a directory
  54. func newDir(nodePath string, createIndex uint64, createTerm uint64,
  55. parent *Node, ACL string, expireTime time.Time) *Node {
  56. return &Node{
  57. Path: nodePath,
  58. CreateIndex: createIndex,
  59. CreateTerm: createTerm,
  60. Parent: parent,
  61. ACL: ACL,
  62. stopExpire: make(chan bool, 1),
  63. ExpireTime: expireTime,
  64. Children: make(map[string]*Node),
  65. }
  66. }
  67. // IsHidden function checks if the node is a hidden node. A hidden node
  68. // will begin with '_'
  69. // A hidden node will not be shown via get command under a directory
  70. // For example if we have /foo/_hidden and /foo/notHidden, get "/foo"
  71. // will only return /foo/notHidden
  72. func (n *Node) IsHidden() bool {
  73. _, name := path.Split(n.Path)
  74. return name[0] == '_'
  75. }
  76. // IsPermanent function checks if the node is a permanent one.
  77. func (n *Node) IsPermanent() bool {
  78. return n.ExpireTime.Sub(Permanent) == 0
  79. }
  80. // IsExpired function checks if the node has been expired.
  81. func (n *Node) IsExpired() (bool, time.Duration) {
  82. if n.IsPermanent() {
  83. return false, 0
  84. }
  85. duration := n.ExpireTime.Sub(time.Now())
  86. if duration <= 0 {
  87. return true, 0
  88. }
  89. return false, duration
  90. }
  91. // IsDir function checks whether the node is a directory.
  92. // If the node is a directory, the function will return true.
  93. // Otherwise the function will return false.
  94. func (n *Node) IsDir() bool {
  95. return !(n.Children == nil)
  96. }
  97. // Remove function remove the node.
  98. func (n *Node) Remove(recursive bool, callback func(path string)) *etcdErr.Error {
  99. if n.IsDir() && !recursive {
  100. // cannot delete a directory without set recursive to true
  101. return etcdErr.NewError(etcdErr.EcodeNotFile, "", UndefIndex, UndefTerm)
  102. }
  103. onceBody := func() {
  104. n.internalRemove(recursive, callback)
  105. }
  106. // this function might be entered multiple times by expire and delete
  107. // every node will only be deleted once.
  108. n.once.Do(onceBody)
  109. return nil
  110. }
  111. // internalRemove function will be called by remove()
  112. func (n *Node) internalRemove(recursive bool, callback func(path string)) {
  113. if !n.IsDir() { // key-value pair
  114. _, name := path.Split(n.Path)
  115. // find its parent and remove the node from the map
  116. if n.Parent != nil && n.Parent.Children[name] == n {
  117. delete(n.Parent.Children, name)
  118. }
  119. if callback != nil {
  120. callback(n.Path)
  121. }
  122. // the stop channel has a buffer. just send to it!
  123. n.stopExpire <- true
  124. return
  125. }
  126. for _, child := range n.Children { // delete all children
  127. child.Remove(true, callback)
  128. }
  129. // delete self
  130. _, name := path.Split(n.Path)
  131. if n.Parent != nil && n.Parent.Children[name] == n {
  132. delete(n.Parent.Children, name)
  133. if callback != nil {
  134. callback(n.Path)
  135. }
  136. n.stopExpire <- true
  137. }
  138. }
  139. // Read function gets the value of the node.
  140. // If the receiver node is not a key-value pair, a "Not A File" error will be returned.
  141. func (n *Node) Read() (string, *etcdErr.Error) {
  142. if n.IsDir() {
  143. return "", etcdErr.NewError(etcdErr.EcodeNotFile, "", UndefIndex, UndefTerm)
  144. }
  145. return n.Value, nil
  146. }
  147. // Write function set the value of the node to the given value.
  148. // If the receiver node is a directory, a "Not A File" error will be returned.
  149. func (n *Node) Write(value string, index uint64, term uint64) *etcdErr.Error {
  150. if n.IsDir() {
  151. return etcdErr.NewError(etcdErr.EcodeNotFile, "", UndefIndex, UndefTerm)
  152. }
  153. n.Value = value
  154. n.ModifiedIndex = index
  155. n.ModifiedTerm = term
  156. return nil
  157. }
  158. // List function return a slice of nodes under the receiver node.
  159. // If the receiver node is not a directory, a "Not A Directory" error will be returned.
  160. func (n *Node) List() ([]*Node, *etcdErr.Error) {
  161. if !n.IsDir() {
  162. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, "", UndefIndex, UndefTerm)
  163. }
  164. nodes := make([]*Node, len(n.Children))
  165. i := 0
  166. for _, node := range n.Children {
  167. nodes[i] = node
  168. i++
  169. }
  170. return nodes, nil
  171. }
  172. // GetChild function returns the child node under the directory node.
  173. // On success, it returns the file node
  174. func (n *Node) GetChild(name string) (*Node, *etcdErr.Error) {
  175. if !n.IsDir() {
  176. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, n.Path, UndefIndex, UndefTerm)
  177. }
  178. child, ok := n.Children[name]
  179. if ok {
  180. return child, nil
  181. }
  182. return nil, nil
  183. }
  184. // Add function adds a node to the receiver node.
  185. // If the receiver is not a directory, a "Not A Directory" error will be returned.
  186. // If there is a existing node with the same name under the directory, a "Already Exist"
  187. // error will be returned
  188. func (n *Node) Add(child *Node) *etcdErr.Error {
  189. if !n.IsDir() {
  190. return etcdErr.NewError(etcdErr.EcodeNotDir, "", UndefIndex, UndefTerm)
  191. }
  192. _, name := path.Split(child.Path)
  193. _, ok := n.Children[name]
  194. if ok {
  195. return etcdErr.NewError(etcdErr.EcodeNodeExist, "", UndefIndex, UndefTerm)
  196. }
  197. n.Children[name] = child
  198. return nil
  199. }
  200. // Expire function will test if the node is expired.
  201. // if the node is already expired, delete the node and return.
  202. // if the node is permanent (this shouldn't happen), return at once.
  203. // else wait for a period time, then remove the node. and notify the watchhub.
  204. func (n *Node) Expire(s *Store) {
  205. expired, duration := n.IsExpired()
  206. if expired { // has been expired
  207. // since the parent function of Expire() runs serially,
  208. // there is no need for lock here
  209. e := newEvent(Expire, n.Path, UndefIndex, UndefTerm)
  210. s.WatcherHub.notify(e)
  211. n.Remove(true, nil)
  212. s.Stats.Inc(ExpireCount)
  213. return
  214. }
  215. if duration == 0 { // Permanent Node
  216. return
  217. }
  218. go func() { // do monitoring
  219. select {
  220. // if timeout, delete the node
  221. case <-time.After(duration):
  222. // before expire get the lock, the expiration time
  223. // of the node may be updated.
  224. // we have to check again when get the lock
  225. s.worldLock.Lock()
  226. defer s.worldLock.Unlock()
  227. expired, _ := n.IsExpired()
  228. if expired {
  229. e := newEvent(Expire, n.Path, UndefIndex, UndefTerm)
  230. s.WatcherHub.notify(e)
  231. n.Remove(true, nil)
  232. s.Stats.Inc(ExpireCount)
  233. }
  234. return
  235. // if stopped, return
  236. case <-n.stopExpire:
  237. return
  238. }
  239. }()
  240. }
  241. func (n *Node) Pair(recurisive, sorted bool) KeyValuePair {
  242. if n.IsDir() {
  243. pair := KeyValuePair{
  244. Key: n.Path,
  245. Dir: true,
  246. }
  247. if !recurisive {
  248. return pair
  249. }
  250. children, _ := n.List()
  251. pair.KVPairs = make([]KeyValuePair, len(children))
  252. // we do not use the index in the children slice directly
  253. // we need to skip the hidden one
  254. i := 0
  255. for _, child := range children {
  256. if child.IsHidden() { // get will not list hidden node
  257. continue
  258. }
  259. pair.KVPairs[i] = child.Pair(recurisive, sorted)
  260. i++
  261. }
  262. // eliminate hidden nodes
  263. pair.KVPairs = pair.KVPairs[:i]
  264. if sorted {
  265. sort.Sort(pair)
  266. }
  267. return pair
  268. }
  269. return KeyValuePair{
  270. Key: n.Path,
  271. Value: n.Value,
  272. }
  273. }
  274. func (n *Node) UpdateTTL(expireTime time.Time, s *Store) {
  275. if !n.IsPermanent() {
  276. // check if the node has been expired
  277. // if the node is not expired, we need to stop the go routine associated with
  278. // that node.
  279. expired, _ := n.IsExpired()
  280. if !expired {
  281. n.stopExpire <- true // suspend it to modify the expiration
  282. }
  283. }
  284. if expireTime.Sub(Permanent) != 0 {
  285. n.ExpireTime = expireTime
  286. n.Expire(s)
  287. }
  288. }
  289. // Clone function clone the node recursively and return the new node.
  290. // If the node is a directory, it will clone all the content under this directory.
  291. // If the node is a key-value pair, it will clone the pair.
  292. func (n *Node) Clone() *Node {
  293. if !n.IsDir() {
  294. return newKV(n.Path, n.Value, n.CreateIndex, n.CreateTerm, n.Parent, n.ACL, n.ExpireTime)
  295. }
  296. clone := newDir(n.Path, n.CreateIndex, n.CreateTerm, n.Parent, n.ACL, n.ExpireTime)
  297. for key, child := range n.Children {
  298. clone.Children[key] = child.Clone()
  299. }
  300. return clone
  301. }
  302. // recoverAndclean function help to do recovery.
  303. // Two things need to be done: 1. recovery structure; 2. delete expired nodes
  304. // If the node is a directory, it will help recover children's parent pointer and recursively
  305. // call this function on its children.
  306. // We check the expire last since we need to recover the whole structure first and add all the
  307. // notifications into the event history.
  308. func (n *Node) recoverAndclean(s *Store) {
  309. if n.IsDir() {
  310. for _, child := range n.Children {
  311. child.Parent = n
  312. child.recoverAndclean(s)
  313. }
  314. }
  315. n.stopExpire = make(chan bool, 1)
  316. n.Expire(s)
  317. }