file_system.go 9.3 KB

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