wfs.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. grace.OnInterrupt(func() {
  107. wfs.metaCache.Shutdown()
  108. })
  109. wfs.root = &Dir{name: wfs.option.FilerMountRootPath, wfs: wfs, id: 1}
  110. wfs.fsNodeCache = newFsCache(wfs.root)
  111. if wfs.option.ConcurrentWriters > 0 {
  112. wfs.concurrentWriters = util.NewLimitedConcurrentExecutor(wfs.option.ConcurrentWriters)
  113. }
  114. return wfs
  115. }
  116. func (wfs *WFS) StartBackgroundTasks() {
  117. startTime := time.Now()
  118. go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.option.FilerMountRootPath, startTime.UnixNano())
  119. }
  120. func (wfs *WFS) Root() (fs.Node, error) {
  121. return wfs.root, nil
  122. }
  123. func (wfs *WFS) AcquireHandle(file *File, uid, gid uint32, writeOnly bool) (fileHandle *FileHandle) {
  124. fullpath := file.fullpath()
  125. glog.V(4).Infof("AcquireHandle %s uid=%d gid=%d", fullpath, uid, gid)
  126. inodeId := file.Id()
  127. wfs.handlesLock.Lock()
  128. existingHandle, found := wfs.handles[inodeId]
  129. wfs.handlesLock.Unlock()
  130. if found && existingHandle != nil {
  131. existingHandle.f.isOpen++
  132. existingHandle.dirtyPages.SetWriteOnly(writeOnly)
  133. glog.V(4).Infof("Acquired Handle %s open %d", fullpath, existingHandle.f.isOpen)
  134. return existingHandle
  135. }
  136. entry, _ := file.maybeLoadEntry(context.Background())
  137. file.entry = entry
  138. fileHandle = newFileHandle(file, uid, gid, writeOnly)
  139. file.isOpen++
  140. wfs.handlesLock.Lock()
  141. wfs.handles[inodeId] = fileHandle
  142. wfs.handlesLock.Unlock()
  143. fileHandle.handle = inodeId
  144. glog.V(4).Infof("Acquired new Handle %s open %d", fullpath, file.isOpen)
  145. return
  146. }
  147. func (wfs *WFS) ReleaseHandle(fullpath util.FullPath, handleId fuse.HandleID) {
  148. wfs.handlesLock.Lock()
  149. defer wfs.handlesLock.Unlock()
  150. glog.V(4).Infof("ReleaseHandle %s id %d current handles length %d", fullpath, handleId, len(wfs.handles))
  151. delete(wfs.handles, uint64(handleId))
  152. return
  153. }
  154. // Statfs is called to obtain file system metadata. Implements fuse.FSStatfser
  155. func (wfs *WFS) Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error {
  156. glog.V(4).Infof("reading fs stats: %+v", req)
  157. if wfs.stats.lastChecked < time.Now().Unix()-20 {
  158. err := wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  159. request := &filer_pb.StatisticsRequest{
  160. Collection: wfs.option.Collection,
  161. Replication: wfs.option.Replication,
  162. Ttl: fmt.Sprintf("%ds", wfs.option.TtlSec),
  163. DiskType: string(wfs.option.DiskType),
  164. }
  165. glog.V(4).Infof("reading filer stats: %+v", request)
  166. resp, err := client.Statistics(context.Background(), request)
  167. if err != nil {
  168. glog.V(0).Infof("reading filer stats %v: %v", request, err)
  169. return err
  170. }
  171. glog.V(4).Infof("read filer stats: %+v", resp)
  172. wfs.stats.TotalSize = resp.TotalSize
  173. wfs.stats.UsedSize = resp.UsedSize
  174. wfs.stats.FileCount = resp.FileCount
  175. wfs.stats.lastChecked = time.Now().Unix()
  176. return nil
  177. })
  178. if err != nil {
  179. glog.V(0).Infof("filer Statistics: %v", err)
  180. return err
  181. }
  182. }
  183. totalDiskSize := wfs.stats.TotalSize
  184. usedDiskSize := wfs.stats.UsedSize
  185. actualFileCount := wfs.stats.FileCount
  186. // Compute the total number of available blocks
  187. resp.Blocks = totalDiskSize / blockSize
  188. // Compute the number of used blocks
  189. numBlocks := uint64(usedDiskSize / blockSize)
  190. // Report the number of free and available blocks for the block size
  191. resp.Bfree = resp.Blocks - numBlocks
  192. resp.Bavail = resp.Blocks - numBlocks
  193. resp.Bsize = uint32(blockSize)
  194. // Report the total number of possible files in the file system (and those free)
  195. resp.Files = math.MaxInt64
  196. resp.Ffree = math.MaxInt64 - actualFileCount
  197. // Report the maximum length of a name and the minimum fragment size
  198. resp.Namelen = 1024
  199. resp.Frsize = uint32(blockSize)
  200. return nil
  201. }
  202. func (wfs *WFS) mapPbIdFromFilerToLocal(entry *filer_pb.Entry) {
  203. if entry.Attributes == nil {
  204. return
  205. }
  206. entry.Attributes.Uid, entry.Attributes.Gid = wfs.option.UidGidMapper.FilerToLocal(entry.Attributes.Uid, entry.Attributes.Gid)
  207. }
  208. func (wfs *WFS) mapPbIdFromLocalToFiler(entry *filer_pb.Entry) {
  209. if entry.Attributes == nil {
  210. return
  211. }
  212. entry.Attributes.Uid, entry.Attributes.Gid = wfs.option.UidGidMapper.LocalToFiler(entry.Attributes.Uid, entry.Attributes.Gid)
  213. }
  214. func (wfs *WFS) LookupFn() wdclient.LookupFileIdFunctionType {
  215. if wfs.option.VolumeServerAccess == "filerProxy" {
  216. return func(fileId string) (targetUrls []string, err error) {
  217. return []string{"http://" + wfs.getCurrentFiler() + "/?proxyChunkId=" + fileId}, nil
  218. }
  219. }
  220. return filer.LookupFn(wfs)
  221. }
  222. func (wfs *WFS) getCurrentFiler() string {
  223. return wfs.option.FilerAddresses[wfs.option.filerIndex]
  224. }
  225. func (option *Option) setupUniqueCacheDirectory() {
  226. cacheUniqueId := util.Md5String([]byte(option.MountDirectory + option.FilerGrpcAddresses[0] + option.FilerMountRootPath + util.Version()))[0:8]
  227. option.uniqueCacheDir = path.Join(option.CacheDir, cacheUniqueId)
  228. option.uniqueCacheTempPageDir = filepath.Join(option.uniqueCacheDir, "sw")
  229. os.MkdirAll(option.uniqueCacheTempPageDir, os.FileMode(0777)&^option.Umask)
  230. }
  231. func (option *Option) getTempFilePageDir() string {
  232. return option.uniqueCacheTempPageDir
  233. }
  234. func (option *Option) getUniqueCacheDir() string {
  235. return option.uniqueCacheDir
  236. }
  237. type NodeWithId uint64
  238. func (n NodeWithId) Id() uint64 {
  239. return uint64(n)
  240. }
  241. func (n NodeWithId) Attr(ctx context.Context, attr *fuse.Attr) error {
  242. return nil
  243. }