node.go 10 KB

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