node.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "path"
  16. "sort"
  17. "time"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/jonboulle/clockwork"
  19. etcdErr "github.com/coreos/etcd/error"
  20. )
  21. // explanations of Compare function result
  22. const (
  23. CompareMatch = 0
  24. CompareIndexNotMatch = 1
  25. CompareValueNotMatch = 2
  26. CompareNotMatch = 3
  27. )
  28. var Permanent time.Time
  29. // node is the basic element in the store system.
  30. // A key-value pair will have a string value
  31. // A directory will have a children map
  32. type node struct {
  33. Path string
  34. CreatedIndex uint64
  35. ModifiedIndex uint64
  36. Parent *node `json:"-"` // should not encode this field! avoid circular dependency.
  37. ExpireTime time.Time
  38. ACL string
  39. Value string // for key-value pair
  40. Children map[string]*node // for directory
  41. // A reference to the store this node is attached to.
  42. store *store
  43. }
  44. // newKV creates a Key-Value pair
  45. func newKV(store *store, nodePath string, value string, createdIndex uint64,
  46. parent *node, ACL string, expireTime time.Time) *node {
  47. return &node{
  48. Path: nodePath,
  49. CreatedIndex: createdIndex,
  50. ModifiedIndex: createdIndex,
  51. Parent: parent,
  52. ACL: ACL,
  53. store: store,
  54. ExpireTime: expireTime,
  55. Value: value,
  56. }
  57. }
  58. // newDir creates a directory
  59. func newDir(store *store, nodePath string, createdIndex uint64, parent *node,
  60. ACL string, expireTime time.Time) *node {
  61. return &node{
  62. Path: nodePath,
  63. CreatedIndex: createdIndex,
  64. ModifiedIndex: createdIndex,
  65. Parent: parent,
  66. ACL: ACL,
  67. ExpireTime: expireTime,
  68. Children: make(map[string]*node),
  69. store: store,
  70. }
  71. }
  72. // IsHidden function checks if the node is a hidden node. A hidden node
  73. // will begin with '_'
  74. // A hidden node will not be shown via get command under a directory
  75. // For example if we have /foo/_hidden and /foo/notHidden, get "/foo"
  76. // will only return /foo/notHidden
  77. func (n *node) IsHidden() bool {
  78. _, name := path.Split(n.Path)
  79. return name[0] == '_'
  80. }
  81. // IsPermanent function checks if the node is a permanent one.
  82. func (n *node) IsPermanent() bool {
  83. // we use a uninitialized time.Time to indicate the node is a
  84. // permanent one.
  85. // the uninitialized time.Time should equal zero.
  86. return n.ExpireTime.IsZero()
  87. }
  88. // IsDir function checks whether the node is a directory.
  89. // If the node is a directory, the function will return true.
  90. // Otherwise the function will return false.
  91. func (n *node) IsDir() bool {
  92. return !(n.Children == nil)
  93. }
  94. // Read function gets the value of the node.
  95. // If the receiver node is not a key-value pair, a "Not A File" error will be returned.
  96. func (n *node) Read() (string, *etcdErr.Error) {
  97. if n.IsDir() {
  98. return "", etcdErr.NewError(etcdErr.EcodeNotFile, "", n.store.CurrentIndex)
  99. }
  100. return n.Value, nil
  101. }
  102. // Write function set the value of the node to the given value.
  103. // If the receiver node is a directory, a "Not A File" error will be returned.
  104. func (n *node) Write(value string, index uint64) *etcdErr.Error {
  105. if n.IsDir() {
  106. return etcdErr.NewError(etcdErr.EcodeNotFile, "", n.store.CurrentIndex)
  107. }
  108. n.Value = value
  109. n.ModifiedIndex = index
  110. return nil
  111. }
  112. func (n *node) expirationAndTTL(clock clockwork.Clock) (*time.Time, int64) {
  113. if !n.IsPermanent() {
  114. /* compute ttl as:
  115. ceiling( (expireTime - timeNow) / nanosecondsPerSecond )
  116. which ranges from 1..n
  117. rather than as:
  118. ( (expireTime - timeNow) / nanosecondsPerSecond ) + 1
  119. which ranges 1..n+1
  120. */
  121. ttlN := n.ExpireTime.Sub(clock.Now())
  122. ttl := ttlN / time.Second
  123. if (ttlN % time.Second) > 0 {
  124. ttl++
  125. }
  126. return &n.ExpireTime, int64(ttl)
  127. }
  128. return nil, 0
  129. }
  130. // List function return a slice of nodes under the receiver node.
  131. // If the receiver node is not a directory, a "Not A Directory" error will be returned.
  132. func (n *node) List() ([]*node, *etcdErr.Error) {
  133. if !n.IsDir() {
  134. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, "", n.store.CurrentIndex)
  135. }
  136. nodes := make([]*node, len(n.Children))
  137. i := 0
  138. for _, node := range n.Children {
  139. nodes[i] = node
  140. i++
  141. }
  142. return nodes, nil
  143. }
  144. // GetChild function returns the child node under the directory node.
  145. // On success, it returns the file node
  146. func (n *node) GetChild(name string) (*node, *etcdErr.Error) {
  147. if !n.IsDir() {
  148. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, n.Path, n.store.CurrentIndex)
  149. }
  150. child, ok := n.Children[name]
  151. if ok {
  152. return child, nil
  153. }
  154. return nil, nil
  155. }
  156. // Add function adds a node to the receiver node.
  157. // If the receiver is not a directory, a "Not A Directory" error will be returned.
  158. // If there is a existing node with the same name under the directory, a "Already Exist"
  159. // error will be returned
  160. func (n *node) Add(child *node) *etcdErr.Error {
  161. if !n.IsDir() {
  162. return etcdErr.NewError(etcdErr.EcodeNotDir, "", n.store.CurrentIndex)
  163. }
  164. _, name := path.Split(child.Path)
  165. _, ok := n.Children[name]
  166. if ok {
  167. return etcdErr.NewError(etcdErr.EcodeNodeExist, "", n.store.CurrentIndex)
  168. }
  169. n.Children[name] = child
  170. return nil
  171. }
  172. // Remove function remove the node.
  173. func (n *node) Remove(dir, recursive bool, callback func(path string)) *etcdErr.Error {
  174. if n.IsDir() {
  175. if !dir {
  176. // cannot delete a directory without recursive set to true
  177. return etcdErr.NewError(etcdErr.EcodeNotFile, n.Path, n.store.CurrentIndex)
  178. }
  179. if len(n.Children) != 0 && !recursive {
  180. // cannot delete a directory if it is not empty and the operation
  181. // is not recursive
  182. return etcdErr.NewError(etcdErr.EcodeDirNotEmpty, n.Path, n.store.CurrentIndex)
  183. }
  184. }
  185. if !n.IsDir() { // key-value pair
  186. _, name := path.Split(n.Path)
  187. // find its parent and remove the node from the map
  188. if n.Parent != nil && n.Parent.Children[name] == n {
  189. delete(n.Parent.Children, name)
  190. }
  191. if callback != nil {
  192. callback(n.Path)
  193. }
  194. if !n.IsPermanent() {
  195. n.store.ttlKeyHeap.remove(n)
  196. }
  197. return nil
  198. }
  199. for _, child := range n.Children { // delete all children
  200. child.Remove(true, 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. }
  213. return nil
  214. }
  215. func (n *node) Repr(recursive, sorted bool, clock clockwork.Clock) *NodeExtern {
  216. if n.IsDir() {
  217. node := &NodeExtern{
  218. Key: n.Path,
  219. Dir: true,
  220. ModifiedIndex: n.ModifiedIndex,
  221. CreatedIndex: n.CreatedIndex,
  222. }
  223. node.Expiration, node.TTL = n.expirationAndTTL(clock)
  224. if !recursive {
  225. return node
  226. }
  227. children, _ := n.List()
  228. node.Nodes = make(NodeExterns, len(children))
  229. // we do not use the index in the children slice directly
  230. // we need to skip the hidden one
  231. i := 0
  232. for _, child := range children {
  233. if child.IsHidden() { // get will not list hidden node
  234. continue
  235. }
  236. node.Nodes[i] = child.Repr(recursive, sorted, clock)
  237. i++
  238. }
  239. // eliminate hidden nodes
  240. node.Nodes = node.Nodes[:i]
  241. if sorted {
  242. sort.Sort(node.Nodes)
  243. }
  244. return node
  245. }
  246. // since n.Value could be changed later, so we need to copy the value out
  247. value := n.Value
  248. node := &NodeExtern{
  249. Key: n.Path,
  250. Value: &value,
  251. ModifiedIndex: n.ModifiedIndex,
  252. CreatedIndex: n.CreatedIndex,
  253. }
  254. node.Expiration, node.TTL = n.expirationAndTTL(clock)
  255. return node
  256. }
  257. func (n *node) UpdateTTL(expireTime time.Time) {
  258. if !n.IsPermanent() {
  259. if expireTime.IsZero() {
  260. // from ttl to permanent
  261. n.ExpireTime = expireTime
  262. // remove from ttl heap
  263. n.store.ttlKeyHeap.remove(n)
  264. } else {
  265. // update ttl
  266. n.ExpireTime = expireTime
  267. // update ttl heap
  268. n.store.ttlKeyHeap.update(n)
  269. }
  270. } else {
  271. if !expireTime.IsZero() {
  272. // from permanent to ttl
  273. n.ExpireTime = expireTime
  274. // push into ttl heap
  275. n.store.ttlKeyHeap.push(n)
  276. }
  277. }
  278. }
  279. // Compare function compares node index and value with provided ones.
  280. // second result value explains result and equals to one of Compare.. constants
  281. func (n *node) Compare(prevValue string, prevIndex uint64) (ok bool, which int) {
  282. indexMatch := (prevIndex == 0 || n.ModifiedIndex == prevIndex)
  283. valueMatch := (prevValue == "" || n.Value == prevValue)
  284. ok = valueMatch && indexMatch
  285. switch {
  286. case valueMatch && indexMatch:
  287. which = CompareMatch
  288. case indexMatch && !valueMatch:
  289. which = CompareValueNotMatch
  290. case valueMatch && !indexMatch:
  291. which = CompareIndexNotMatch
  292. default:
  293. which = CompareNotMatch
  294. }
  295. return
  296. }
  297. // Clone function clone the node recursively and return the new node.
  298. // If the node is a directory, it will clone all the content under this directory.
  299. // If the node is a key-value pair, it will clone the pair.
  300. func (n *node) Clone() *node {
  301. if !n.IsDir() {
  302. return newKV(n.store, n.Path, n.Value, n.CreatedIndex, n.Parent, n.ACL, n.ExpireTime)
  303. }
  304. clone := newDir(n.store, n.Path, n.CreatedIndex, n.Parent, n.ACL, n.ExpireTime)
  305. for key, child := range n.Children {
  306. clone.Children[key] = child.Clone()
  307. }
  308. return clone
  309. }
  310. // recoverAndclean function help to do recovery.
  311. // Two things need to be done: 1. recovery structure; 2. delete expired nodes
  312. // If the node is a directory, it will help recover children's parent pointer and recursively
  313. // call this function on its children.
  314. // We check the expire last since we need to recover the whole structure first and add all the
  315. // notifications into the event history.
  316. func (n *node) recoverAndclean() {
  317. if n.IsDir() {
  318. for _, child := range n.Children {
  319. child.Parent = n
  320. child.store = n.store
  321. child.recoverAndclean()
  322. }
  323. }
  324. if !n.ExpireTime.IsZero() {
  325. n.store.ttlKeyHeap.push(n)
  326. }
  327. }