file_system.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package fileSystem
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path"
  6. "sort"
  7. "strings"
  8. "time"
  9. etcdErr "github.com/coreos/etcd/error"
  10. )
  11. type FileSystem struct {
  12. Root *Node
  13. WatcherHub *watcherHub
  14. Index uint64
  15. Term uint64
  16. }
  17. func New() *FileSystem {
  18. return &FileSystem{
  19. Root: newDir("/", 0, 0, nil, "", Permanent),
  20. WatcherHub: newWatchHub(1000),
  21. }
  22. }
  23. func (fs *FileSystem) Get(nodePath string, recursive, sorted bool, index uint64, term uint64) (*Event, error) {
  24. nodePath = path.Clean(path.Join("/", nodePath))
  25. n, err := fs.InternalGet(nodePath, index, term)
  26. if err != nil {
  27. return nil, err
  28. }
  29. e := newEvent(Get, nodePath, index, term)
  30. if n.IsDir() { // node is dir
  31. e.Dir = true
  32. children, _ := n.List()
  33. e.KVPairs = make([]KeyValuePair, len(children))
  34. // we do not use the index in the children slice directly
  35. // we need to skip the hidden one
  36. i := 0
  37. for _, child := range children {
  38. if child.IsHidden() { // get will not list hidden node
  39. continue
  40. }
  41. e.KVPairs[i] = child.Pair(recursive, sorted)
  42. i++
  43. }
  44. // eliminate hidden nodes
  45. e.KVPairs = e.KVPairs[:i]
  46. rootPairs := KeyValuePair{
  47. KVPairs: e.KVPairs,
  48. }
  49. if sorted {
  50. sort.Sort(rootPairs)
  51. }
  52. } else { // node is file
  53. e.Value = n.Value
  54. }
  55. if n.ExpireTime.Sub(Permanent) != 0 {
  56. e.Expiration = &n.ExpireTime
  57. e.TTL = int64(n.ExpireTime.Sub(time.Now())/time.Second) + 1
  58. }
  59. return e, nil
  60. }
  61. // Create function creates the Node at nodePath. Create will help to create intermediate directories with no ttl.
  62. // If the node has already existed, create will fail.
  63. // If any node on the path is a file, create will fail.
  64. func (fs *FileSystem) Create(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  65. nodePath = path.Clean(path.Join("/", nodePath))
  66. // make sure we can create the node
  67. _, err := fs.InternalGet(nodePath, index, term)
  68. if err == nil { // key already exists
  69. return nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath)
  70. }
  71. etcdError, _ := err.(etcdErr.Error)
  72. if etcdError.ErrorCode == 104 { // we cannot create the key due to meet a file while walking
  73. return nil, err
  74. }
  75. dir, _ := path.Split(nodePath)
  76. // walk through the nodePath, create dirs and get the last directory node
  77. d, err := fs.walk(dir, fs.checkDir)
  78. if err != nil {
  79. return nil, err
  80. }
  81. e := newEvent(Create, nodePath, fs.Index, fs.Term)
  82. var n *Node
  83. if len(value) != 0 { // create file
  84. e.Value = value
  85. n = newFile(nodePath, value, fs.Index, fs.Term, d, "", expireTime)
  86. } else { // create directory
  87. e.Dir = true
  88. n = newDir(nodePath, fs.Index, fs.Term, d, "", expireTime)
  89. }
  90. err = d.Add(n)
  91. if err != nil {
  92. return nil, err
  93. }
  94. // Node with TTL
  95. if expireTime.Sub(Permanent) != 0 {
  96. n.Expire()
  97. e.Expiration = &n.ExpireTime
  98. e.TTL = int64(expireTime.Sub(time.Now())/time.Second) + 1
  99. }
  100. fs.WatcherHub.notify(e)
  101. return e, nil
  102. }
  103. // Update function updates the value/ttl of the node.
  104. // If the node is a file, the value and the ttl can be updated.
  105. // If the node is a directory, only the ttl can be updated.
  106. func (fs *FileSystem) Update(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  107. n, err := fs.InternalGet(nodePath, index, term)
  108. if err != nil { // if the node does not exist, return error
  109. return nil, err
  110. }
  111. e := newEvent(Update, nodePath, fs.Index, fs.Term)
  112. if n.IsDir() { // if the node is a directory, we can only update ttl
  113. if len(value) != 0 {
  114. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)
  115. }
  116. } else { // if the node is a file, we can update value and ttl
  117. e.PrevValue = n.Value
  118. if len(value) != 0 {
  119. e.Value = value
  120. }
  121. n.Write(value, index, term)
  122. }
  123. // update ttl
  124. if !n.IsPermanent() {
  125. n.stopExpire <- true
  126. }
  127. if expireTime.Sub(Permanent) != 0 {
  128. n.ExpireTime = expireTime
  129. n.Expire()
  130. e.Expiration = &n.ExpireTime
  131. e.TTL = int64(expireTime.Sub(time.Now())/time.Second) + 1
  132. }
  133. fs.WatcherHub.notify(e)
  134. return e, nil
  135. }
  136. func (fs *FileSystem) TestAndSet(nodePath string, prevValue string, prevIndex uint64,
  137. value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {
  138. f, err := fs.InternalGet(nodePath, index, term)
  139. if err != nil {
  140. return nil, err
  141. }
  142. if f.IsDir() { // can only test and set file
  143. return nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)
  144. }
  145. if f.Value == prevValue || f.ModifiedIndex == prevIndex {
  146. // if test succeed, write the value
  147. e := newEvent(TestAndSet, nodePath, index, term)
  148. e.PrevValue = f.Value
  149. e.Value = value
  150. f.Write(value, index, term)
  151. fs.WatcherHub.notify(e)
  152. return e, nil
  153. }
  154. cause := fmt.Sprintf("[%v != %v] [%v != %v]", prevValue, f.Value, prevIndex, f.ModifiedIndex)
  155. return nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause)
  156. }
  157. // Delete function deletes the node at the given path.
  158. // If the node is a directory, recursive must be true to delete it.
  159. func (fs *FileSystem) Delete(nodePath string, recursive bool, index uint64, term uint64) (*Event, error) {
  160. n, err := fs.InternalGet(nodePath, index, term)
  161. if err != nil { // if the node does not exist, return error
  162. return nil, err
  163. }
  164. e := newEvent(Delete, nodePath, index, term)
  165. if n.IsDir() {
  166. e.Dir = true
  167. } else {
  168. e.PrevValue = n.Value
  169. }
  170. callback := func(path string) { // notify function
  171. fs.WatcherHub.notifyWithPath(e, path, true)
  172. }
  173. err = n.Remove(recursive, callback)
  174. if err != nil {
  175. return nil, err
  176. }
  177. fs.WatcherHub.notify(e)
  178. return e, nil
  179. }
  180. func (fs *FileSystem) Watch(prefix string, recursive bool, sinceIndex uint64, index uint64, term uint64) (<-chan *Event, error) {
  181. fs.Index, fs.Term = index, term
  182. if sinceIndex == 0 {
  183. return fs.WatcherHub.watch(prefix, recursive, index+1)
  184. }
  185. return fs.WatcherHub.watch(prefix, recursive, sinceIndex)
  186. }
  187. // walk function walks all the nodePath and apply the walkFunc on each directory
  188. func (fs *FileSystem) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, error)) (*Node, error) {
  189. components := strings.Split(nodePath, "/")
  190. curr := fs.Root
  191. var err error
  192. for i := 1; i < len(components); i++ {
  193. if len(components[i]) == 0 { // ignore empty string
  194. return curr, nil
  195. }
  196. curr, err = walkFunc(curr, components[i])
  197. if err != nil {
  198. return nil, err
  199. }
  200. }
  201. return curr, nil
  202. }
  203. // InternalGet function get the node of the given nodePath.
  204. func (fs *FileSystem) InternalGet(nodePath string, index uint64, term uint64) (*Node, error) {
  205. nodePath = path.Clean(path.Join("/", nodePath))
  206. // update file system known index and term
  207. fs.Index, fs.Term = index, term
  208. walkFunc := func(parent *Node, name string) (*Node, error) {
  209. if !parent.IsDir() {
  210. return nil, etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path)
  211. }
  212. child, ok := parent.Children[name]
  213. if ok {
  214. return child, nil
  215. }
  216. return nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name))
  217. }
  218. f, err := fs.walk(nodePath, walkFunc)
  219. if err != nil {
  220. return nil, err
  221. }
  222. return f, nil
  223. }
  224. // checkDir function will check whether the component is a directory under parent node.
  225. // If it is a directory, this function will return the pointer to that node.
  226. // If it does not exist, this function will create a new directory and return the pointer to that node.
  227. // If it is a file, this function will return error.
  228. func (fs *FileSystem) checkDir(parent *Node, dirName string) (*Node, error) {
  229. subDir, ok := parent.Children[dirName]
  230. if ok {
  231. return subDir, nil
  232. }
  233. n := newDir(path.Join(parent.Path, dirName), fs.Index, fs.Term, parent, parent.ACL, Permanent)
  234. parent.Children[dirName] = n
  235. return n, nil
  236. }
  237. // Save function saves the static state of the store system.
  238. // Save function will not be able to save the state of watchers.
  239. // Save function will not save the parent field of the node. Or there will
  240. // be cyclic dependencies issue for the json package.
  241. func (fs *FileSystem) Save() ([]byte, error) {
  242. cloneFs := New()
  243. cloneFs.Root = fs.Root.Clone()
  244. b, err := json.Marshal(fs)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return b, nil
  249. }
  250. // recovery function recovery the store system from a static state.
  251. // It needs to recovery the parent field of the nodes.
  252. // It needs to delete the expired nodes since the saved time and also
  253. // need to create monitor go routines.
  254. func (fs *FileSystem) Recovery(state []byte) error {
  255. err := json.Unmarshal(state, fs)
  256. if err != nil {
  257. return err
  258. }
  259. fs.Root.recoverAndclean()
  260. return nil
  261. }