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.

253 lines
6.9 KiB

7 years ago
5 years ago
5 years ago
6 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
  1. package filesys
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "github.com/chrislusf/seaweedfs/weed/wdclient"
  7. "math"
  8. "os"
  9. "path"
  10. "sync"
  11. "time"
  12. "google.golang.org/grpc"
  13. "github.com/chrislusf/seaweedfs/weed/util/grace"
  14. "github.com/seaweedfs/fuse"
  15. "github.com/seaweedfs/fuse/fs"
  16. "github.com/chrislusf/seaweedfs/weed/filesys/meta_cache"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  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. MountDirectory string
  24. FilerAddress string
  25. FilerGrpcAddress string
  26. GrpcDialOption grpc.DialOption
  27. FilerMountRootPath string
  28. Collection string
  29. Replication string
  30. TtlSec int32
  31. ChunkSizeLimit int64
  32. ConcurrentWriters int
  33. CacheDir string
  34. CacheSizeMB int64
  35. DataCenter string
  36. EntryCacheTtl time.Duration
  37. Umask os.FileMode
  38. MountUid uint32
  39. MountGid uint32
  40. MountMode os.FileMode
  41. MountCtime time.Time
  42. MountMtime time.Time
  43. OutsideContainerClusterMode bool // whether the mount runs outside SeaweedFS containers
  44. Cipher bool // whether encrypt data on volume server
  45. UidGidMapper *meta_cache.UidGidMapper
  46. }
  47. var _ = fs.FS(&WFS{})
  48. var _ = fs.FSStatfser(&WFS{})
  49. type WFS struct {
  50. option *Option
  51. // contains all open handles, protected by handlesLock
  52. handlesLock sync.Mutex
  53. handles map[uint64]*FileHandle
  54. bufPool sync.Pool
  55. stats statsCache
  56. root fs.Node
  57. fsNodeCache *FsCache
  58. chunkCache *chunk_cache.TieredChunkCache
  59. metaCache *meta_cache.MetaCache
  60. signature int32
  61. // throttle writers
  62. concurrentWriters *util.LimitedConcurrentExecutor
  63. }
  64. type statsCache struct {
  65. filer_pb.StatisticsResponse
  66. lastChecked int64 // unix time in seconds
  67. }
  68. func NewSeaweedFileSystem(option *Option) *WFS {
  69. wfs := &WFS{
  70. option: option,
  71. handles: make(map[uint64]*FileHandle),
  72. bufPool: sync.Pool{
  73. New: func() interface{} {
  74. return make([]byte, option.ChunkSizeLimit)
  75. },
  76. },
  77. signature: util.RandomInt32(),
  78. }
  79. cacheUniqueId := util.Md5String([]byte(option.MountDirectory + option.FilerGrpcAddress + option.FilerMountRootPath + util.Version()))[0:8]
  80. cacheDir := path.Join(option.CacheDir, cacheUniqueId)
  81. if option.CacheSizeMB > 0 {
  82. os.MkdirAll(cacheDir, os.FileMode(0777)&^option.Umask)
  83. wfs.chunkCache = chunk_cache.NewTieredChunkCache(256, cacheDir, option.CacheSizeMB, 1024*1024)
  84. }
  85. wfs.metaCache = meta_cache.NewMetaCache(path.Join(cacheDir, "meta"), util.FullPath(option.FilerMountRootPath), option.UidGidMapper, func(filePath util.FullPath) {
  86. fsNode := wfs.fsNodeCache.GetFsNode(filePath)
  87. if fsNode != nil {
  88. if file, ok := fsNode.(*File); ok {
  89. file.clearEntry()
  90. }
  91. }
  92. })
  93. startTime := time.Now()
  94. go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.option.FilerMountRootPath, startTime.UnixNano())
  95. grace.OnInterrupt(func() {
  96. wfs.metaCache.Shutdown()
  97. })
  98. entry, _ := filer_pb.GetEntry(wfs, util.FullPath(wfs.option.FilerMountRootPath))
  99. wfs.root = &Dir{name: wfs.option.FilerMountRootPath, wfs: wfs, entry: entry}
  100. wfs.fsNodeCache = newFsCache(wfs.root)
  101. if wfs.option.ConcurrentWriters > 0 {
  102. wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(wfs.option.ConcurrentWriters)
  103. }
  104. return wfs
  105. }
  106. func (wfs *WFS) Root() (fs.Node, error) {
  107. return wfs.root, nil
  108. }
  109. func (wfs *WFS) AcquireHandle(file *File, uid, gid uint32) (fileHandle *FileHandle) {
  110. fullpath := file.fullpath()
  111. glog.V(4).Infof("AcquireHandle %s uid=%d gid=%d", fullpath, uid, gid)
  112. wfs.handlesLock.Lock()
  113. defer wfs.handlesLock.Unlock()
  114. inodeId := file.fullpath().AsInode()
  115. if file.isOpen > 0 {
  116. existingHandle, found := wfs.handles[inodeId]
  117. if found && existingHandle != nil {
  118. file.isOpen++
  119. return existingHandle
  120. }
  121. }
  122. fileHandle = newFileHandle(file, uid, gid)
  123. file.maybeLoadEntry(context.Background())
  124. file.isOpen++
  125. wfs.handles[inodeId] = fileHandle
  126. fileHandle.handle = inodeId
  127. return
  128. }
  129. func (wfs *WFS) ReleaseHandle(fullpath util.FullPath, handleId fuse.HandleID) {
  130. wfs.handlesLock.Lock()
  131. defer wfs.handlesLock.Unlock()
  132. glog.V(4).Infof("%s ReleaseHandle id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  133. delete(wfs.handles, fullpath.AsInode())
  134. return
  135. }
  136. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  137. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  138. glog.V(4).Infof("reading fs stats: %+v", req)
  139. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  140. err := wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  141. request := &filer_pb.StatisticsRequest{
  142. Collection: wfs.option.Collection,
  143. Replication: wfs.option.Replication,
  144. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  145. }
  146. glog.V(4).Infof("reading filer stats: %+v", request)
  147. resp, err := client.Statistics(context.Background(), request)
  148. if err != nil {
  149. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  150. return err
  151. }
  152. glog.V(4).Infof("read filer stats: %+v", resp)
  153. wfs.stats.TotalSize = resp.TotalSize
  154. wfs.stats.UsedSize = resp.UsedSize
  155. wfs.stats.FileCount = resp.FileCount
  156. wfs.stats.lastChecked = time.Now().Unix()
  157. return nil
  158. })
  159. if err != nil {
  160. glog.V(0).Infof("filer Statistics: %v", err)
  161. return err
  162. }
  163. }
  164. totalDiskSize := wfs.stats.TotalSize
  165. usedDiskSize := wfs.stats.UsedSize
  166. actualFileCount := wfs.stats.FileCount
  167. // Compute the total number of available blocks
  168. resp.Blocks = totalDiskSize / blockSize
  169. // Compute the number of used blocks
  170. numBlocks := uint64(usedDiskSize / blockSize)
  171. // Report the number of free and available blocks for the block size
  172. resp.Bfree = resp.Blocks - numBlocks
  173. resp.Bavail = resp.Blocks - numBlocks
  174. resp.Bsize = uint32(blockSize)
  175. // Report the total number of possible files in the file system (and those free)
  176. resp.Files = math.MaxInt64
  177. resp.Ffree = math.MaxInt64 - actualFileCount
  178. // Report the maximum length of a name and the minimum fragment size
  179. resp.Namelen = 1024
  180. resp.Frsize = uint32(blockSize)
  181. return nil
  182. }
  183. func (wfs *WFS) mapPbIdFromFilerToLocal(entry *filer_pb.Entry) {
  184. if entry.Attributes == nil {
  185. return
  186. }
  187. entry.Attributes.Uid, entry.Attributes.Gid = wfs.option.UidGidMapper.FilerToLocal(entry.Attributes.Uid, entry.Attributes.Gid)
  188. }
  189. func (wfs *WFS) mapPbIdFromLocalToFiler(entry *filer_pb.Entry) {
  190. if entry.Attributes == nil {
  191. return
  192. }
  193. entry.Attributes.Uid, entry.Attributes.Gid = wfs.option.UidGidMapper.LocalToFiler(entry.Attributes.Uid, entry.Attributes.Gid)
  194. }
  195. func (wfs *WFS) LookupFn() wdclient.LookupFileIdFunctionType {
  196. if wfs.option.OutsideContainerClusterMode {
  197. return func(fileId string) (targetUrls []string, err error) {
  198. return []string{"http://" + wfs.option.FilerAddress + "/?proxyChunkId=" + fileId}, nil
  199. }
  200. }
  201. return filer.LookupFn(wfs)
  202. }