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.

237 lines
6.1 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
5 years ago
6 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. "google.golang.org/grpc"
  12. "github.com/chrislusf/seaweedfs/weed/util/grace"
  13. "github.com/seaweedfs/fuse"
  14. "github.com/seaweedfs/fuse/fs"
  15. "github.com/chrislusf/seaweedfs/weed/filesys/meta_cache"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/pb"
  18. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. "github.com/chrislusf/seaweedfs/weed/util/chunk_cache"
  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. }
  44. var _ = fs.FS(&WFS{})
  45. var _ = fs.FSStatfser(&WFS{})
  46. type WFS struct {
  47. option *Option
  48. // contains all open handles, protected by handlesLock
  49. handlesLock sync.Mutex
  50. handles map[uint64]*FileHandle
  51. bufPool sync.Pool
  52. stats statsCache
  53. root fs.Node
  54. chunkCache *chunk_cache.ChunkCache
  55. metaCache *meta_cache.MetaCache
  56. }
  57. type statsCache struct {
  58. filer_pb.StatisticsResponse
  59. lastChecked int64 // unix time in seconds
  60. }
  61. func NewSeaweedFileSystem(option *Option) *WFS {
  62. wfs := &WFS{
  63. option: option,
  64. handles: make(map[uint64]*FileHandle),
  65. bufPool: sync.Pool{
  66. New: func() interface{} {
  67. return make([]byte, option.ChunkSizeLimit)
  68. },
  69. },
  70. }
  71. if option.CacheSizeMB > 0 {
  72. os.MkdirAll(option.CacheDir, 0755)
  73. wfs.chunkCache = chunk_cache.NewChunkCache(256, option.CacheDir, option.CacheSizeMB)
  74. grace.OnInterrupt(func() {
  75. wfs.chunkCache.Shutdown()
  76. })
  77. }
  78. wfs.metaCache = meta_cache.NewMetaCache(path.Join(option.CacheDir, "meta"))
  79. startTime := time.Now()
  80. if err := meta_cache.InitMetaCache(wfs.metaCache, wfs, wfs.option.FilerMountRootPath); err != nil {
  81. glog.V(0).Infof("failed to init meta cache: %v", err)
  82. } else {
  83. go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs, wfs.option.FilerMountRootPath, startTime.UnixNano())
  84. grace.OnInterrupt(func() {
  85. wfs.metaCache.Shutdown()
  86. })
  87. }
  88. wfs.root = &Dir{name: wfs.option.FilerMountRootPath, wfs: wfs}
  89. return wfs
  90. }
  91. func (wfs *WFS) Root() (fs.Node, error) {
  92. return wfs.root, nil
  93. }
  94. var _ = filer_pb.FilerClient(&WFS{})
  95. func (wfs *WFS) WithFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  96. err := pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  97. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  98. return fn(client)
  99. }, wfs.option.FilerGrpcAddress, wfs.option.GrpcDialOption)
  100. if err == nil {
  101. return nil
  102. }
  103. return err
  104. }
  105. func (wfs *WFS) AcquireHandle(file *File, uid, gid uint32) (fileHandle *FileHandle) {
  106. fullpath := file.fullpath()
  107. glog.V(4).Infof("%s AcquireHandle uid=%d gid=%d", fullpath, uid, gid)
  108. wfs.handlesLock.Lock()
  109. defer wfs.handlesLock.Unlock()
  110. inodeId := file.fullpath().AsInode()
  111. existingHandle, found := wfs.handles[inodeId]
  112. if found && existingHandle != nil {
  113. return existingHandle
  114. }
  115. fileHandle = newFileHandle(file, uid, gid)
  116. wfs.handles[inodeId] = fileHandle
  117. fileHandle.handle = inodeId
  118. glog.V(4).Infof("%s new fh %d", fullpath, fileHandle.handle)
  119. return
  120. }
  121. func (wfs *WFS) ReleaseHandle(fullpath util.FullPath, handleId fuse.HandleID) {
  122. wfs.handlesLock.Lock()
  123. defer wfs.handlesLock.Unlock()
  124. glog.V(4).Infof("%s ReleaseHandle id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  125. delete(wfs.handles, fullpath.AsInode())
  126. return
  127. }
  128. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  129. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  130. glog.V(4).Infof("reading fs stats: %+v", req)
  131. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  132. err := wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  133. request := &filer_pb.StatisticsRequest{
  134. Collection: wfs.option.Collection,
  135. Replication: wfs.option.Replication,
  136. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  137. }
  138. glog.V(4).Infof("reading filer stats: %+v", request)
  139. resp, err := client.Statistics(context.Background(), request)
  140. if err != nil {
  141. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  142. return err
  143. }
  144. glog.V(4).Infof("read filer stats: %+v", resp)
  145. wfs.stats.TotalSize = resp.TotalSize
  146. wfs.stats.UsedSize = resp.UsedSize
  147. wfs.stats.FileCount = resp.FileCount
  148. wfs.stats.lastChecked = time.Now().Unix()
  149. return nil
  150. })
  151. if err != nil {
  152. glog.V(0).Infof("filer Statistics: %v", err)
  153. return err
  154. }
  155. }
  156. totalDiskSize := wfs.stats.TotalSize
  157. usedDiskSize := wfs.stats.UsedSize
  158. actualFileCount := wfs.stats.FileCount
  159. // Compute the total number of available blocks
  160. resp.Blocks = totalDiskSize / blockSize
  161. // Compute the number of used blocks
  162. numBlocks := uint64(usedDiskSize / blockSize)
  163. // Report the number of free and available blocks for the block size
  164. resp.Bfree = resp.Blocks - numBlocks
  165. resp.Bavail = resp.Blocks - numBlocks
  166. resp.Bsize = uint32(blockSize)
  167. // Report the total number of possible files in the file system (and those free)
  168. resp.Files = math.MaxInt64
  169. resp.Ffree = math.MaxInt64 - actualFileCount
  170. // Report the maximum length of a name and the minimum fragment size
  171. resp.Namelen = 1024
  172. resp.Frsize = uint32(blockSize)
  173. return nil
  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. }