You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

244 lines
6.4 KiB

5 years ago
7 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package filesys
  2. import (
  3. "context"
  4. "fmt"
  5. "math"
  6. "os"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/karlseguin/ccache"
  11. "google.golang.org/grpc"
  12. "github.com/chrislusf/seaweedfs/weed/glog"
  13. "github.com/chrislusf/seaweedfs/weed/pb"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. "github.com/seaweedfs/fuse"
  17. "github.com/seaweedfs/fuse/fs"
  18. )
  19. type Option struct {
  20. FilerGrpcAddress string
  21. GrpcDialOption grpc.DialOption
  22. FilerMountRootPath string
  23. Collection string
  24. Replication string
  25. TtlSec int32
  26. ChunkSizeLimit int64
  27. DataCenter string
  28. DirListCacheLimit int64
  29. EntryCacheTtl time.Duration
  30. Umask os.FileMode
  31. MountUid uint32
  32. MountGid uint32
  33. MountMode os.FileMode
  34. MountCtime time.Time
  35. MountMtime time.Time
  36. OutsideContainerClusterMode bool // whether the mount runs outside SeaweedFS containers
  37. Cipher bool // whether encrypt data on volume server
  38. }
  39. var _ = fs.FS(&WFS{})
  40. var _ = fs.FSStatfser(&WFS{})
  41. type WFS struct {
  42. option *Option
  43. listDirectoryEntriesCache *ccache.Cache
  44. // contains all open handles, protected by handlesLock
  45. handlesLock sync.Mutex
  46. handles []*FileHandle
  47. pathToHandleIndex map[util.FullPath]int
  48. bufPool sync.Pool
  49. stats statsCache
  50. root fs.Node
  51. fsNodeCache *FsCache
  52. }
  53. type statsCache struct {
  54. filer_pb.StatisticsResponse
  55. lastChecked int64 // unix time in seconds
  56. }
  57. func NewSeaweedFileSystem(option *Option) *WFS {
  58. wfs := &WFS{
  59. option: option,
  60. listDirectoryEntriesCache: ccache.New(ccache.Configure().MaxSize(option.DirListCacheLimit * 3).ItemsToPrune(100)),
  61. pathToHandleIndex: make(map[util.FullPath]int),
  62. bufPool: sync.Pool{
  63. New: func() interface{} {
  64. return make([]byte, option.ChunkSizeLimit)
  65. },
  66. },
  67. }
  68. wfs.root = &Dir{name: wfs.option.FilerMountRootPath, wfs: wfs}
  69. wfs.fsNodeCache = newFsCache(wfs.root)
  70. return wfs
  71. }
  72. func (wfs *WFS) Root() (fs.Node, error) {
  73. return wfs.root, nil
  74. }
  75. func (wfs *WFS) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  76. err := pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  77. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  78. return fn(client)
  79. }, wfs.option.FilerGrpcAddress, wfs.option.GrpcDialOption)
  80. if err == nil {
  81. return nil
  82. }
  83. return err
  84. }
  85. func (wfs *WFS) AcquireHandle(file *File, uid, gid uint32) (fileHandle *FileHandle) {
  86. fullpath := file.fullpath()
  87. glog.V(4).Infof("%s AcquireHandle uid=%d gid=%d", fullpath, uid, gid)
  88. wfs.handlesLock.Lock()
  89. defer wfs.handlesLock.Unlock()
  90. index, found := wfs.pathToHandleIndex[fullpath]
  91. if found && wfs.handles[index] != nil {
  92. glog.V(2).Infoln(fullpath, "found fileHandle id", index)
  93. return wfs.handles[index]
  94. }
  95. fileHandle = newFileHandle(file, uid, gid)
  96. for i, h := range wfs.handles {
  97. if h == nil {
  98. wfs.handles[i] = fileHandle
  99. fileHandle.handle = uint64(i)
  100. wfs.pathToHandleIndex[fullpath] = i
  101. glog.V(4).Infof("%s reuse fh %d", fullpath, fileHandle.handle)
  102. return
  103. }
  104. }
  105. wfs.handles = append(wfs.handles, fileHandle)
  106. fileHandle.handle = uint64(len(wfs.handles) - 1)
  107. wfs.pathToHandleIndex[fullpath] = int(fileHandle.handle)
  108. glog.V(4).Infof("%s new fh %d", fullpath, fileHandle.handle)
  109. return
  110. }
  111. func (wfs *WFS) ReleaseHandle(fullpath util.FullPath, handleId fuse.HandleID) {
  112. wfs.handlesLock.Lock()
  113. defer wfs.handlesLock.Unlock()
  114. glog.V(4).Infof("%s ReleaseHandle id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  115. delete(wfs.pathToHandleIndex, fullpath)
  116. if int(handleId) < len(wfs.handles) {
  117. wfs.handles[int(handleId)] = nil
  118. }
  119. return
  120. }
  121. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  122. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  123. glog.V(4).Infof("reading fs stats: %+v", req)
  124. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  125. err := wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  126. request := &filer_pb.StatisticsRequest{
  127. Collection: wfs.option.Collection,
  128. Replication: wfs.option.Replication,
  129. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  130. }
  131. glog.V(4).Infof("reading filer stats: %+v", request)
  132. resp, err := client.Statistics(context.Background(), request)
  133. if err != nil {
  134. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  135. return err
  136. }
  137. glog.V(4).Infof("read filer stats: %+v", resp)
  138. wfs.stats.TotalSize = resp.TotalSize
  139. wfs.stats.UsedSize = resp.UsedSize
  140. wfs.stats.FileCount = resp.FileCount
  141. wfs.stats.lastChecked = time.Now().Unix()
  142. return nil
  143. })
  144. if err != nil {
  145. glog.V(0).Infof("filer Statistics: %v", err)
  146. return err
  147. }
  148. }
  149. totalDiskSize := wfs.stats.TotalSize
  150. usedDiskSize := wfs.stats.UsedSize
  151. actualFileCount := wfs.stats.FileCount
  152. // Compute the total number of available blocks
  153. resp.Blocks = totalDiskSize / blockSize
  154. // Compute the number of used blocks
  155. numBlocks := uint64(usedDiskSize / blockSize)
  156. // Report the number of free and available blocks for the block size
  157. resp.Bfree = resp.Blocks - numBlocks
  158. resp.Bavail = resp.Blocks - numBlocks
  159. resp.Bsize = uint32(blockSize)
  160. // Report the total number of possible files in the file system (and those free)
  161. resp.Files = math.MaxInt64
  162. resp.Ffree = math.MaxInt64 - actualFileCount
  163. // Report the maximum length of a name and the minimum fragment size
  164. resp.Namelen = 1024
  165. resp.Frsize = uint32(blockSize)
  166. return nil
  167. }
  168. func (wfs *WFS) cacheGet(path util.FullPath) *filer_pb.Entry {
  169. item := wfs.listDirectoryEntriesCache.Get(string(path))
  170. if item != nil && !item.Expired() {
  171. return item.Value().(*filer_pb.Entry)
  172. }
  173. return nil
  174. }
  175. func (wfs *WFS) cacheSet(path util.FullPath, entry *filer_pb.Entry, ttl time.Duration) {
  176. if entry == nil {
  177. wfs.listDirectoryEntriesCache.Delete(string(path))
  178. } else {
  179. wfs.listDirectoryEntriesCache.Set(string(path), entry, ttl)
  180. }
  181. }
  182. func (wfs *WFS) cacheDelete(path util.FullPath) {
  183. wfs.listDirectoryEntriesCache.Delete(string(path))
  184. }
  185. func (wfs *WFS) AdjustedUrl(hostAndPort string) string {
  186. if !wfs.option.OutsideContainerClusterMode {
  187. return hostAndPort
  188. }
  189. commaIndex := strings.Index(hostAndPort, ":")
  190. if commaIndex < 0 {
  191. return hostAndPort
  192. }
  193. filerCommaIndex := strings.Index(wfs.option.FilerGrpcAddress, ":")
  194. return fmt.Sprintf("%s:%s", wfs.option.FilerGrpcAddress[:filerCommaIndex], hostAndPort[commaIndex+1:])
  195. }