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.

248 lines
6.5 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. }
  84. wfs.root = &Dir{name: wfs.option.FilerMountRootPath, wfs: wfs}
  85. wfs.fsNodeCache = newFsCache(wfs.root)
  86. return wfs
  87. }
  88. func (wfs *WFS) Root() (fs.Node, error) {
  89. return wfs.root, nil
  90. }
  91. func (wfs *WFS) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  92. err := pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  93. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  94. return fn(client)
  95. }, wfs.option.FilerGrpcAddress, wfs.option.GrpcDialOption)
  96. if err == nil {
  97. return nil
  98. }
  99. return err
  100. }
  101. func (wfs *WFS) AcquireHandle(file *File, uid, gid uint32) (fileHandle *FileHandle) {
  102. fullpath := file.fullpath()
  103. glog.V(4).Infof("%s AcquireHandle uid=%d gid=%d", fullpath, uid, gid)
  104. wfs.handlesLock.Lock()
  105. defer wfs.handlesLock.Unlock()
  106. inodeId := file.fullpath().AsInode()
  107. existingHandle, found := wfs.handles[inodeId]
  108. if found && existingHandle != nil {
  109. return existingHandle
  110. }
  111. fileHandle = newFileHandle(file, uid, gid)
  112. wfs.handles[inodeId] = fileHandle
  113. fileHandle.handle = inodeId
  114. glog.V(4).Infof("%s new fh %d", fullpath, fileHandle.handle)
  115. return
  116. }
  117. func (wfs *WFS) ReleaseHandle(fullpath util.FullPath, handleId fuse.HandleID) {
  118. wfs.handlesLock.Lock()
  119. defer wfs.handlesLock.Unlock()
  120. glog.V(4).Infof("%s ReleaseHandle id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  121. delete(wfs.handles, fullpath.AsInode())
  122. return
  123. }
  124. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  125. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  126. glog.V(4).Infof("reading fs stats: %+v", req)
  127. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  128. err := wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  129. request := &filer_pb.StatisticsRequest{
  130. Collection: wfs.option.Collection,
  131. Replication: wfs.option.Replication,
  132. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  133. }
  134. glog.V(4).Infof("reading filer stats: %+v", request)
  135. resp, err := client.Statistics(context.Background(), request)
  136. if err != nil {
  137. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  138. return err
  139. }
  140. glog.V(4).Infof("read filer stats: %+v", resp)
  141. wfs.stats.TotalSize = resp.TotalSize
  142. wfs.stats.UsedSize = resp.UsedSize
  143. wfs.stats.FileCount = resp.FileCount
  144. wfs.stats.lastChecked = time.Now().Unix()
  145. return nil
  146. })
  147. if err != nil {
  148. glog.V(0).Infof("filer Statistics: %v", err)
  149. return err
  150. }
  151. }
  152. totalDiskSize := wfs.stats.TotalSize
  153. usedDiskSize := wfs.stats.UsedSize
  154. actualFileCount := wfs.stats.FileCount
  155. // Compute the total number of available blocks
  156. resp.Blocks = totalDiskSize / blockSize
  157. // Compute the number of used blocks
  158. numBlocks := uint64(usedDiskSize / blockSize)
  159. // Report the number of free and available blocks for the block size
  160. resp.Bfree = resp.Blocks - numBlocks
  161. resp.Bavail = resp.Blocks - numBlocks
  162. resp.Bsize = uint32(blockSize)
  163. // Report the total number of possible files in the file system (and those free)
  164. resp.Files = math.MaxInt64
  165. resp.Ffree = math.MaxInt64 - actualFileCount
  166. // Report the maximum length of a name and the minimum fragment size
  167. resp.Namelen = 1024
  168. resp.Frsize = uint32(blockSize)
  169. return nil
  170. }
  171. func (wfs *WFS) cacheGet(path util.FullPath) *filer_pb.Entry {
  172. item := wfs.listDirectoryEntriesCache.Get(string(path))
  173. if item != nil && !item.Expired() {
  174. return item.Value().(*filer_pb.Entry)
  175. }
  176. return nil
  177. }
  178. func (wfs *WFS) cacheSet(path util.FullPath, entry *filer_pb.Entry, ttl time.Duration) {
  179. if entry == nil {
  180. wfs.listDirectoryEntriesCache.Delete(string(path))
  181. } else {
  182. wfs.listDirectoryEntriesCache.Set(string(path), entry, ttl)
  183. }
  184. }
  185. func (wfs *WFS) cacheDelete(path util.FullPath) {
  186. wfs.listDirectoryEntriesCache.Delete(string(path))
  187. }
  188. func (wfs *WFS) AdjustedUrl(hostAndPort string) string {
  189. if !wfs.option.OutsideContainerClusterMode {
  190. return hostAndPort
  191. }
  192. commaIndex := strings.Index(hostAndPort, ":")
  193. if commaIndex < 0 {
  194. return hostAndPort
  195. }
  196. filerCommaIndex := strings.Index(wfs.option.FilerGrpcAddress, ":")
  197. return fmt.Sprintf("%s:%s", wfs.option.FilerGrpcAddress[:filerCommaIndex], hostAndPort[commaIndex+1:])
  198. }