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.

260 lines
6.8 KiB

5 years ago
7 years ago
6 years ago
6 years ago
6 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/filer2"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. "github.com/seaweedfs/fuse"
  17. "github.com/seaweedfs/fuse/fs"
  18. )
  19. type Option struct {
  20. FilerGrpcAddress string
  21. GrpcDialOption grpc.DialOption
  22. FilerMountRootPath string
  23. Collection string
  24. Replication string
  25. TtlSec int32
  26. ChunkSizeLimit int64
  27. DataCenter string
  28. DirListCacheLimit int64
  29. EntryCacheTtl time.Duration
  30. Umask os.FileMode
  31. MountUid uint32
  32. MountGid uint32
  33. MountMode os.FileMode
  34. MountCtime time.Time
  35. MountMtime time.Time
  36. }
  37. var _ = fs.FS(&WFS{})
  38. var _ = fs.FSStatfser(&WFS{})
  39. type WFS struct {
  40. option *Option
  41. listDirectoryEntriesCache *ccache.Cache
  42. // contains all open handles, protected by handlesLock
  43. handlesLock sync.Mutex
  44. handles []*FileHandle
  45. pathToHandleIndex map[filer2.FullPath]int
  46. bufPool sync.Pool
  47. stats statsCache
  48. // nodes, protected by nodesLock
  49. nodesLock sync.Mutex
  50. nodes map[uint64]fs.Node
  51. root fs.Node
  52. }
  53. type statsCache struct {
  54. filer_pb.StatisticsResponse
  55. lastChecked int64 // unix time in seconds
  56. }
  57. func NewSeaweedFileSystem(option *Option) *WFS {
  58. wfs := &WFS{
  59. option: option,
  60. listDirectoryEntriesCache: ccache.New(ccache.Configure().MaxSize(option.DirListCacheLimit * 3).ItemsToPrune(100)),
  61. pathToHandleIndex: make(map[filer2.FullPath]int),
  62. bufPool: sync.Pool{
  63. New: func() interface{} {
  64. return make([]byte, option.ChunkSizeLimit)
  65. },
  66. },
  67. nodes: make(map[uint64]fs.Node),
  68. }
  69. wfs.root = &Dir{Path: wfs.option.FilerMountRootPath, wfs: wfs}
  70. return wfs
  71. }
  72. func (wfs *WFS) Root() (fs.Node, error) {
  73. return wfs.root, nil
  74. }
  75. func (wfs *WFS) WithFilerClient(ctx context.Context, fn func(filer_pb.SeaweedFilerClient) error) error {
  76. err := util.WithCachedGrpcClient(ctx, func(grpcConnection *grpc.ClientConn) error {
  77. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  78. return fn(client)
  79. }, wfs.option.FilerGrpcAddress, wfs.option.GrpcDialOption)
  80. if err == nil {
  81. return nil
  82. }
  83. if strings.Contains(err.Error(), "context canceled") {
  84. time.Sleep(1337 * time.Millisecond)
  85. glog.V(2).Infoln("retry context canceled request...")
  86. return util.WithCachedGrpcClient(context.Background(), func(grpcConnection *grpc.ClientConn) error {
  87. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  88. return fn(client)
  89. }, wfs.option.FilerGrpcAddress, wfs.option.GrpcDialOption)
  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. index, found := wfs.pathToHandleIndex[fullpath]
  99. if found && wfs.handles[index] != nil {
  100. glog.V(2).Infoln(fullpath, "found fileHandle id", index)
  101. return wfs.handles[index]
  102. }
  103. fileHandle = newFileHandle(file, uid, gid)
  104. for i, h := range wfs.handles {
  105. if h == nil {
  106. wfs.handles[i] = fileHandle
  107. fileHandle.handle = uint64(i)
  108. wfs.pathToHandleIndex[fullpath] = i
  109. glog.V(4).Infof("%s reuse fh %d", fullpath, fileHandle.handle)
  110. return
  111. }
  112. }
  113. wfs.handles = append(wfs.handles, fileHandle)
  114. fileHandle.handle = uint64(len(wfs.handles) - 1)
  115. wfs.pathToHandleIndex[fullpath] = int(fileHandle.handle)
  116. glog.V(4).Infof("%s new fh %d", fullpath, fileHandle.handle)
  117. return
  118. }
  119. func (wfs *WFS) ReleaseHandle(fullpath filer2.FullPath, handleId fuse.HandleID) {
  120. wfs.handlesLock.Lock()
  121. defer wfs.handlesLock.Unlock()
  122. glog.V(4).Infof("%s ReleaseHandle id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  123. delete(wfs.pathToHandleIndex, fullpath)
  124. if int(handleId) < len(wfs.handles) {
  125. wfs.handles[int(handleId)] = nil
  126. }
  127. return
  128. }
  129. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  130. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  131. glog.V(4).Infof("reading fs stats: %+v", req)
  132. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  133. err := wfs.WithFilerClient(ctx, func(client filer_pb.SeaweedFilerClient) error {
  134. request := &filer_pb.StatisticsRequest{
  135. Collection: wfs.option.Collection,
  136. Replication: wfs.option.Replication,
  137. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  138. }
  139. glog.V(4).Infof("reading filer stats: %+v", request)
  140. resp, err := client.Statistics(ctx, request)
  141. if err != nil {
  142. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  143. return err
  144. }
  145. glog.V(4).Infof("read filer stats: %+v", resp)
  146. wfs.stats.TotalSize = resp.TotalSize
  147. wfs.stats.UsedSize = resp.UsedSize
  148. wfs.stats.FileCount = resp.FileCount
  149. wfs.stats.lastChecked = time.Now().Unix()
  150. return nil
  151. })
  152. if err != nil {
  153. glog.V(0).Infof("filer Statistics: %v", err)
  154. return err
  155. }
  156. }
  157. totalDiskSize := wfs.stats.TotalSize
  158. usedDiskSize := wfs.stats.UsedSize
  159. actualFileCount := wfs.stats.FileCount
  160. // Compute the total number of available blocks
  161. resp.Blocks = totalDiskSize / blockSize
  162. // Compute the number of used blocks
  163. numBlocks := uint64(usedDiskSize / blockSize)
  164. // Report the number of free and available blocks for the block size
  165. resp.Bfree = resp.Blocks - numBlocks
  166. resp.Bavail = resp.Blocks - numBlocks
  167. resp.Bsize = uint32(blockSize)
  168. // Report the total number of possible files in the file system (and those free)
  169. resp.Files = math.MaxInt64
  170. resp.Ffree = math.MaxInt64 - actualFileCount
  171. // Report the maximum length of a name and the minimum fragment size
  172. resp.Namelen = 1024
  173. resp.Frsize = uint32(blockSize)
  174. return nil
  175. }
  176. func (wfs *WFS) cacheGet(path filer2.FullPath) *filer_pb.Entry {
  177. item := wfs.listDirectoryEntriesCache.Get(string(path))
  178. if item != nil && !item.Expired() {
  179. return item.Value().(*filer_pb.Entry)
  180. }
  181. return nil
  182. }
  183. func (wfs *WFS) cacheSet(path filer2.FullPath, entry *filer_pb.Entry, ttl time.Duration) {
  184. if entry == nil {
  185. wfs.listDirectoryEntriesCache.Delete(string(path))
  186. } else {
  187. wfs.listDirectoryEntriesCache.Set(string(path), entry, ttl)
  188. }
  189. }
  190. func (wfs *WFS) cacheDelete(path filer2.FullPath) {
  191. wfs.listDirectoryEntriesCache.Delete(string(path))
  192. }
  193. func (wfs *WFS) getNode(fullpath filer2.FullPath, fn func() fs.Node) fs.Node {
  194. wfs.nodesLock.Lock()
  195. defer wfs.nodesLock.Unlock()
  196. node, found := wfs.nodes[fullpath.AsInode()]
  197. if found {
  198. return node
  199. }
  200. node = fn()
  201. if node != nil {
  202. wfs.nodes[fullpath.AsInode()] = node
  203. }
  204. return node
  205. }
  206. func (wfs *WFS) forgetNode(fullpath filer2.FullPath) {
  207. wfs.nodesLock.Lock()
  208. defer wfs.nodesLock.Unlock()
  209. delete(wfs.nodes, fullpath.AsInode())
  210. }