node.go 10.0 KB

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