node.go 10 KB

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