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.

240 lines
6.2 KiB

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