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.

299 lines
8.4 KiB

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