node.go 9.9 KB

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