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.

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