swarmfs_unix.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // +build linux darwin freebsd
  17. package api
  18. import (
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "sync"
  25. "time"
  26. "bazil.org/fuse"
  27. "bazil.org/fuse/fs"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/swarm/storage"
  31. )
  32. var (
  33. inode uint64 = 1
  34. inodeLock sync.RWMutex
  35. )
  36. var (
  37. errEmptyMountPoint = errors.New("need non-empty mount point")
  38. errMaxMountCount = errors.New("max FUSE mount count reached")
  39. errMountTimeout = errors.New("mount timeout")
  40. )
  41. func isFUSEUnsupportedError(err error) bool {
  42. if perr, ok := err.(*os.PathError); ok {
  43. return perr.Op == "open" && perr.Path == "/dev/fuse"
  44. }
  45. return err == fuse.ErrOSXFUSENotFound
  46. }
  47. // MountInfo contains information about every active mount
  48. type MountInfo struct {
  49. MountPoint string
  50. ManifestHash string
  51. resolvedKey storage.Key
  52. rootDir *Dir
  53. fuseConnection *fuse.Conn
  54. }
  55. // newInode creates a new inode number.
  56. // Inode numbers need to be unique, they are used for caching inside fuse
  57. func newInode() uint64 {
  58. inodeLock.Lock()
  59. defer inodeLock.Unlock()
  60. inode += 1
  61. return inode
  62. }
  63. func (self *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) {
  64. if mountpoint == "" {
  65. return nil, errEmptyMountPoint
  66. }
  67. cleanedMountPoint, err := filepath.Abs(filepath.Clean(mountpoint))
  68. if err != nil {
  69. return nil, err
  70. }
  71. self.activeLock.Lock()
  72. defer self.activeLock.Unlock()
  73. noOfActiveMounts := len(self.activeMounts)
  74. if noOfActiveMounts >= maxFuseMounts {
  75. return nil, errMaxMountCount
  76. }
  77. if _, ok := self.activeMounts[cleanedMountPoint]; ok {
  78. return nil, fmt.Errorf("%s is already mounted", cleanedMountPoint)
  79. }
  80. uri, err := Parse("bzz:/" + mhash)
  81. if err != nil {
  82. return nil, err
  83. }
  84. key, err := self.swarmApi.Resolve(uri)
  85. if err != nil {
  86. return nil, err
  87. }
  88. path := uri.Path
  89. if len(path) > 0 {
  90. path += "/"
  91. }
  92. quitC := make(chan bool)
  93. trie, err := loadManifest(self.swarmApi.dpa, key, quitC)
  94. if err != nil {
  95. return nil, fmt.Errorf("can't load manifest %v: %v", key.String(), err)
  96. }
  97. dirTree := map[string]*Dir{}
  98. rootDir := &Dir{
  99. inode: newInode(),
  100. name: "root",
  101. directories: nil,
  102. files: nil,
  103. }
  104. dirTree["root"] = rootDir
  105. err = trie.listWithPrefix(path, quitC, func(entry *manifestTrieEntry, suffix string) {
  106. key = common.Hex2Bytes(entry.Hash)
  107. fullpath := "/" + suffix
  108. basepath := filepath.Dir(fullpath)
  109. filename := filepath.Base(fullpath)
  110. parentDir := rootDir
  111. dirUntilNow := ""
  112. paths := strings.Split(basepath, "/")
  113. for i := range paths {
  114. if paths[i] != "" {
  115. thisDir := paths[i]
  116. dirUntilNow = dirUntilNow + "/" + thisDir
  117. if _, ok := dirTree[dirUntilNow]; !ok {
  118. dirTree[dirUntilNow] = &Dir{
  119. inode: newInode(),
  120. name: thisDir,
  121. path: dirUntilNow,
  122. directories: nil,
  123. files: nil,
  124. }
  125. parentDir.directories = append(parentDir.directories, dirTree[dirUntilNow])
  126. parentDir = dirTree[dirUntilNow]
  127. } else {
  128. parentDir = dirTree[dirUntilNow]
  129. }
  130. }
  131. }
  132. thisFile := &File{
  133. inode: newInode(),
  134. name: filename,
  135. path: fullpath,
  136. key: key,
  137. swarmApi: self.swarmApi,
  138. }
  139. parentDir.files = append(parentDir.files, thisFile)
  140. })
  141. fconn, err := fuse.Mount(cleanedMountPoint, fuse.FSName("swarmfs"), fuse.VolumeName(mhash))
  142. if err != nil {
  143. fuse.Unmount(cleanedMountPoint)
  144. log.Warn("Error mounting swarm manifest", "mountpoint", cleanedMountPoint, "err", err)
  145. return nil, err
  146. }
  147. mounterr := make(chan error, 1)
  148. go func() {
  149. filesys := &FS{root: rootDir}
  150. if err := fs.Serve(fconn, filesys); err != nil {
  151. mounterr <- err
  152. }
  153. }()
  154. // Check if the mount process has an error to report.
  155. select {
  156. case <-time.After(mountTimeout):
  157. fuse.Unmount(cleanedMountPoint)
  158. return nil, errMountTimeout
  159. case err := <-mounterr:
  160. log.Warn("Error serving swarm FUSE FS", "mountpoint", cleanedMountPoint, "err", err)
  161. return nil, err
  162. case <-fconn.Ready:
  163. log.Info("Now serving swarm FUSE FS", "manifest", mhash, "mountpoint", cleanedMountPoint)
  164. }
  165. // Assemble and Store the mount information for future use
  166. mi := &MountInfo{
  167. MountPoint: cleanedMountPoint,
  168. ManifestHash: mhash,
  169. resolvedKey: key,
  170. rootDir: rootDir,
  171. fuseConnection: fconn,
  172. }
  173. self.activeMounts[cleanedMountPoint] = mi
  174. return mi, nil
  175. }
  176. func (self *SwarmFS) Unmount(mountpoint string) (bool, error) {
  177. self.activeLock.Lock()
  178. defer self.activeLock.Unlock()
  179. cleanedMountPoint, err := filepath.Abs(filepath.Clean(mountpoint))
  180. if err != nil {
  181. return false, err
  182. }
  183. mountInfo := self.activeMounts[cleanedMountPoint]
  184. if mountInfo == nil || mountInfo.MountPoint != cleanedMountPoint {
  185. return false, fmt.Errorf("%s is not mounted", cleanedMountPoint)
  186. }
  187. err = fuse.Unmount(cleanedMountPoint)
  188. if err != nil {
  189. // TODO(jmozah): try forceful unmount if normal unmount fails
  190. return false, err
  191. }
  192. // remove the mount information from the active map
  193. mountInfo.fuseConnection.Close()
  194. delete(self.activeMounts, cleanedMountPoint)
  195. return true, nil
  196. }
  197. func (self *SwarmFS) Listmounts() []*MountInfo {
  198. self.activeLock.RLock()
  199. defer self.activeLock.RUnlock()
  200. rows := make([]*MountInfo, 0, len(self.activeMounts))
  201. for _, mi := range self.activeMounts {
  202. rows = append(rows, mi)
  203. }
  204. return rows
  205. }
  206. func (self *SwarmFS) Stop() bool {
  207. for mp := range self.activeMounts {
  208. mountInfo := self.activeMounts[mp]
  209. self.Unmount(mountInfo.MountPoint)
  210. }
  211. return true
  212. }