node.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. package store
  2. import (
  3. "path"
  4. "sort"
  5. "time"
  6. etcdErr "github.com/coreos/etcd/error"
  7. ustrings "github.com/coreos/etcd/pkg/strings"
  8. )
  9. var Permanent time.Time
  10. // node is the basic element in the store system.
  11. // A key-value pair will have a string value
  12. // A directory will have a children map
  13. type node struct {
  14. Path string
  15. CreatedIndex uint64
  16. ModifiedIndex uint64
  17. Parent *node `json:"-"` // should not encode this field! avoid circular dependency.
  18. ExpireTime time.Time
  19. ACL string
  20. Value string // for key-value pair
  21. Children map[string]*node // for directory
  22. // A reference to the store this node is attached to.
  23. store *store
  24. }
  25. // newKV creates a Key-Value pair
  26. func newKV(store *store, nodePath string, value string, createdIndex uint64,
  27. parent *node, ACL string, expireTime time.Time) *node {
  28. return &node{
  29. Path: nodePath,
  30. CreatedIndex: createdIndex,
  31. ModifiedIndex: createdIndex,
  32. Parent: parent,
  33. ACL: ACL,
  34. store: store,
  35. ExpireTime: expireTime,
  36. Value: value,
  37. }
  38. }
  39. // newDir creates a directory
  40. func newDir(store *store, nodePath string, createdIndex uint64, parent *node,
  41. ACL string, expireTime time.Time) *node {
  42. return &node{
  43. Path: nodePath,
  44. CreatedIndex: createdIndex,
  45. ModifiedIndex: createdIndex,
  46. Parent: parent,
  47. ACL: ACL,
  48. ExpireTime: expireTime,
  49. Children: make(map[string]*node),
  50. store: store,
  51. }
  52. }
  53. // IsHidden function checks if the node is a hidden node. A hidden node
  54. // will begin with '_'
  55. // A hidden node will not be shown via get command under a directory
  56. // For example if we have /foo/_hidden and /foo/notHidden, get "/foo"
  57. // will only return /foo/notHidden
  58. func (n *node) IsHidden() bool {
  59. _, name := path.Split(n.Path)
  60. return name[0] == '_'
  61. }
  62. // IsPermanent function checks if the node is a permanent one.
  63. func (n *node) IsPermanent() bool {
  64. // we use a uninitialized time.Time to indicate the node is a
  65. // permanent one.
  66. // the uninitialized time.Time should equal zero.
  67. return n.ExpireTime.IsZero()
  68. }
  69. // IsDir function checks whether the node is a directory.
  70. // If the node is a directory, the function will return true.
  71. // Otherwise the function will return false.
  72. func (n *node) IsDir() bool {
  73. return !(n.Children == nil)
  74. }
  75. // Read function gets the value of the node.
  76. // If the receiver node is not a key-value pair, a "Not A File" error will be returned.
  77. func (n *node) Read() (string, *etcdErr.Error) {
  78. if n.IsDir() {
  79. return "", etcdErr.NewError(etcdErr.EcodeNotFile, "", n.store.Index())
  80. }
  81. return n.Value, nil
  82. }
  83. // Write function set the value of the node to the given value.
  84. // If the receiver node is a directory, a "Not A File" error will be returned.
  85. func (n *node) Write(value string, index uint64) *etcdErr.Error {
  86. if n.IsDir() {
  87. return etcdErr.NewError(etcdErr.EcodeNotFile, "", n.store.Index())
  88. }
  89. n.Value = value
  90. n.ModifiedIndex = index
  91. return nil
  92. }
  93. func (n *node) ExpirationAndTTL() (*time.Time, int64) {
  94. if !n.IsPermanent() {
  95. /* compute ttl as:
  96. ceiling( (expireTime - timeNow) / nanosecondsPerSecond )
  97. which ranges from 1..n
  98. rather than as:
  99. ( (expireTime - timeNow) / nanosecondsPerSecond ) + 1
  100. which ranges 1..n+1
  101. */
  102. ttlN := n.ExpireTime.Sub(time.Now())
  103. ttl := ttlN / time.Second
  104. if (ttlN % time.Second) > 0 {
  105. ttl++
  106. }
  107. return &n.ExpireTime, int64(ttl)
  108. }
  109. return nil, 0
  110. }
  111. // List function return a slice of nodes under the receiver node.
  112. // If the receiver node is not a directory, a "Not A Directory" error will be returned.
  113. func (n *node) List() ([]*node, *etcdErr.Error) {
  114. if !n.IsDir() {
  115. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, "", n.store.Index())
  116. }
  117. nodes := make([]*node, len(n.Children))
  118. i := 0
  119. for _, node := range n.Children {
  120. nodes[i] = node
  121. i++
  122. }
  123. return nodes, nil
  124. }
  125. // GetChild function returns the child node under the directory node.
  126. // On success, it returns the file node
  127. func (n *node) GetChild(name string) (*node, *etcdErr.Error) {
  128. if !n.IsDir() {
  129. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, n.Path, n.store.Index())
  130. }
  131. child, ok := n.Children[name]
  132. if ok {
  133. return child, nil
  134. }
  135. return nil, nil
  136. }
  137. // Add function adds a node to the receiver node.
  138. // If the receiver is not a directory, a "Not A Directory" error will be returned.
  139. // If there is a existing node with the same name under the directory, a "Already Exist"
  140. // error will be returned
  141. func (n *node) Add(child *node) *etcdErr.Error {
  142. if !n.IsDir() {
  143. return etcdErr.NewError(etcdErr.EcodeNotDir, "", n.store.Index())
  144. }
  145. _, name := path.Split(child.Path)
  146. _, ok := n.Children[name]
  147. if ok {
  148. return etcdErr.NewError(etcdErr.EcodeNodeExist, "", n.store.Index())
  149. }
  150. n.Children[name] = child
  151. return nil
  152. }
  153. // Remove function remove the node.
  154. func (n *node) Remove(dir, recursive bool, callback func(path string)) *etcdErr.Error {
  155. if n.IsDir() {
  156. if !dir {
  157. // cannot delete a directory without recursive set to true
  158. return etcdErr.NewError(etcdErr.EcodeNotFile, n.Path, n.store.Index())
  159. }
  160. if len(n.Children) != 0 && !recursive {
  161. // cannot delete a directory if it is not empty and the operation
  162. // is not recursive
  163. return etcdErr.NewError(etcdErr.EcodeDirNotEmpty, n.Path, n.store.Index())
  164. }
  165. }
  166. if !n.IsDir() { // key-value pair
  167. _, name := path.Split(n.Path)
  168. // find its parent and remove the node from the map
  169. if n.Parent != nil && n.Parent.Children[name] == n {
  170. delete(n.Parent.Children, name)
  171. }
  172. if callback != nil {
  173. callback(n.Path)
  174. }
  175. if !n.IsPermanent() {
  176. n.store.ttlKeyHeap.remove(n)
  177. }
  178. return nil
  179. }
  180. for _, child := range n.Children { // delete all children
  181. child.Remove(true, true, callback)
  182. }
  183. // delete self
  184. _, name := path.Split(n.Path)
  185. if n.Parent != nil && n.Parent.Children[name] == n {
  186. delete(n.Parent.Children, name)
  187. if callback != nil {
  188. callback(n.Path)
  189. }
  190. if !n.IsPermanent() {
  191. n.store.ttlKeyHeap.remove(n)
  192. }
  193. }
  194. return nil
  195. }
  196. func (n *node) Repr(recurisive, sorted bool) *NodeExtern {
  197. if n.IsDir() {
  198. node := &NodeExtern{
  199. Key: n.Path,
  200. Dir: true,
  201. ModifiedIndex: n.ModifiedIndex,
  202. CreatedIndex: n.CreatedIndex,
  203. }
  204. node.Expiration, node.TTL = n.ExpirationAndTTL()
  205. if !recurisive {
  206. return node
  207. }
  208. children, _ := n.List()
  209. node.Nodes = make(NodeExterns, len(children))
  210. // we do not use the index in the children slice directly
  211. // we need to skip the hidden one
  212. i := 0
  213. for _, child := range children {
  214. if child.IsHidden() { // get will not list hidden node
  215. continue
  216. }
  217. node.Nodes[i] = child.Repr(recurisive, sorted)
  218. i++
  219. }
  220. // eliminate hidden nodes
  221. node.Nodes = node.Nodes[:i]
  222. if sorted {
  223. sort.Sort(node.Nodes)
  224. }
  225. return node
  226. }
  227. // since n.Value could be changed later, so we need to copy the value out
  228. value := ustrings.Clone(n.Value)
  229. node := &NodeExtern{
  230. Key: n.Path,
  231. Value: &value,
  232. ModifiedIndex: n.ModifiedIndex,
  233. CreatedIndex: n.CreatedIndex,
  234. }
  235. node.Expiration, node.TTL = n.ExpirationAndTTL()
  236. return node
  237. }
  238. func (n *node) UpdateTTL(expireTime time.Time) {
  239. if !n.IsPermanent() {
  240. if expireTime.IsZero() {
  241. // from ttl to permanent
  242. // remove from ttl heap
  243. n.store.ttlKeyHeap.remove(n)
  244. } else {
  245. // update ttl
  246. n.ExpireTime = expireTime
  247. // update ttl heap
  248. n.store.ttlKeyHeap.update(n)
  249. }
  250. } else {
  251. if !expireTime.IsZero() {
  252. // from permanent to ttl
  253. n.ExpireTime = expireTime
  254. // push into ttl heap
  255. n.store.ttlKeyHeap.push(n)
  256. }
  257. }
  258. }
  259. func (n *node) Compare(prevValue string, prevIndex uint64) bool {
  260. compareValue := (prevValue == "" || n.Value == prevValue)
  261. compareIndex := (prevIndex == 0 || n.ModifiedIndex == prevIndex)
  262. return compareValue && compareIndex
  263. }
  264. // Clone function clone the node recursively and return the new node.
  265. // If the node is a directory, it will clone all the content under this directory.
  266. // If the node is a key-value pair, it will clone the pair.
  267. func (n *node) Clone() *node {
  268. if !n.IsDir() {
  269. return newKV(n.store, n.Path, n.Value, n.CreatedIndex, n.Parent, n.ACL, n.ExpireTime)
  270. }
  271. clone := newDir(n.store, n.Path, n.CreatedIndex, n.Parent, n.ACL, n.ExpireTime)
  272. for key, child := range n.Children {
  273. clone.Children[key] = child.Clone()
  274. }
  275. return clone
  276. }
  277. // recoverAndclean function help to do recovery.
  278. // Two things need to be done: 1. recovery structure; 2. delete expired nodes
  279. // If the node is a directory, it will help recover children's parent pointer and recursively
  280. // call this function on its children.
  281. // We check the expire last since we need to recover the whole structure first and add all the
  282. // notifications into the event history.
  283. func (n *node) recoverAndclean() {
  284. if n.IsDir() {
  285. for _, child := range n.Children {
  286. child.Parent = n
  287. child.store = n.store
  288. child.recoverAndclean()
  289. }
  290. }
  291. if !n.ExpireTime.IsZero() {
  292. n.store.ttlKeyHeap.push(n)
  293. }
  294. }