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.

235 lines
6.1 KiB

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