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.

317 lines
8.3 KiB

7 years ago
7 years ago
4 years ago
7 years ago
4 years ago
4 years ago
7 years ago
4 years ago
5 years ago
5 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
5 years ago
6 years ago
4 years ago
  1. package filesys
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net/http"
  8. "os"
  9. "sync"
  10. "time"
  11. "github.com/seaweedfs/fuse"
  12. "github.com/seaweedfs/fuse/fs"
  13. "github.com/chrislusf/seaweedfs/weed/filer"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. )
  17. type FileHandle struct {
  18. // cache file has been written to
  19. dirtyPages DirtyPages
  20. entryViewCache []filer.VisibleInterval
  21. reader io.ReaderAt
  22. contentType string
  23. handle uint64
  24. sync.Mutex
  25. f *File
  26. RequestId fuse.RequestID // unique ID for request
  27. NodeId fuse.NodeID // file or directory the request is about
  28. Uid uint32 // user ID of process making request
  29. Gid uint32 // group ID of process making request
  30. writeOnly bool
  31. }
  32. func newFileHandle(file *File, uid, gid uint32, writeOnly bool) *FileHandle {
  33. fh := &FileHandle{
  34. f: file,
  35. dirtyPages: newContinuousDirtyPages(file, writeOnly),
  36. Uid: uid,
  37. Gid: gid,
  38. }
  39. entry := fh.f.getEntry()
  40. if entry != nil {
  41. entry.Attributes.FileSize = filer.FileSize(entry)
  42. }
  43. return fh
  44. }
  45. var _ = fs.Handle(&FileHandle{})
  46. // var _ = fs.HandleReadAller(&FileHandle{})
  47. var _ = fs.HandleReader(&FileHandle{})
  48. var _ = fs.HandleFlusher(&FileHandle{})
  49. var _ = fs.HandleWriter(&FileHandle{})
  50. var _ = fs.HandleReleaser(&FileHandle{})
  51. func (fh *FileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
  52. glog.V(4).Infof("%s read fh %d: [%d,%d) size %d resp.Data cap=%d", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(req.Size), req.Size, cap(resp.Data))
  53. fh.Lock()
  54. defer fh.Unlock()
  55. if req.Size <= 0 {
  56. return nil
  57. }
  58. buff := resp.Data[:cap(resp.Data)]
  59. if req.Size > cap(resp.Data) {
  60. // should not happen
  61. buff = make([]byte, req.Size)
  62. }
  63. totalRead, err := fh.readFromChunks(buff, req.Offset)
  64. if err == nil || err == io.EOF {
  65. maxStop := fh.readFromDirtyPages(buff, req.Offset)
  66. totalRead = max(maxStop-req.Offset, totalRead)
  67. }
  68. if err == io.EOF {
  69. err = nil
  70. }
  71. if err != nil {
  72. glog.Warningf("file handle read %s %d: %v", fh.f.fullpath(), totalRead, err)
  73. return fuse.EIO
  74. }
  75. if totalRead > int64(len(buff)) {
  76. glog.Warningf("%s FileHandle Read %d: [%d,%d) size %d totalRead %d", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(req.Size), req.Size, totalRead)
  77. totalRead = min(int64(len(buff)), totalRead)
  78. }
  79. if err == nil {
  80. resp.Data = buff[:totalRead]
  81. }
  82. return err
  83. }
  84. func (fh *FileHandle) readFromDirtyPages(buff []byte, startOffset int64) (maxStop int64) {
  85. maxStop = fh.dirtyPages.ReadDirtyDataAt(buff, startOffset)
  86. return
  87. }
  88. func (fh *FileHandle) readFromChunks(buff []byte, offset int64) (int64, error) {
  89. entry := fh.f.getEntry()
  90. if entry == nil {
  91. return 0, io.EOF
  92. }
  93. fileSize := int64(filer.FileSize(entry))
  94. fileFullPath := fh.f.fullpath()
  95. if fileSize == 0 {
  96. glog.V(1).Infof("empty fh %v", fileFullPath)
  97. return 0, io.EOF
  98. }
  99. if offset+int64(len(buff)) <= int64(len(entry.Content)) {
  100. totalRead := copy(buff, entry.Content[offset:])
  101. glog.V(4).Infof("file handle read cached %s [%d,%d] %d", fileFullPath, offset, offset+int64(totalRead), totalRead)
  102. return int64(totalRead), nil
  103. }
  104. var chunkResolveErr error
  105. if fh.entryViewCache == nil {
  106. fh.entryViewCache, chunkResolveErr = filer.NonOverlappingVisibleIntervals(fh.f.wfs.LookupFn(), entry.Chunks)
  107. if chunkResolveErr != nil {
  108. return 0, fmt.Errorf("fail to resolve chunk manifest: %v", chunkResolveErr)
  109. }
  110. fh.reader = nil
  111. }
  112. reader := fh.reader
  113. if reader == nil {
  114. chunkViews := filer.ViewFromVisibleIntervals(fh.entryViewCache, 0, math.MaxInt64)
  115. reader = filer.NewChunkReaderAtFromClient(fh.f.wfs.LookupFn(), chunkViews, fh.f.wfs.chunkCache, fileSize)
  116. }
  117. fh.reader = reader
  118. totalRead, err := reader.ReadAt(buff, offset)
  119. if err != nil && err != io.EOF {
  120. glog.Errorf("file handle read %s: %v", fileFullPath, err)
  121. }
  122. glog.V(4).Infof("file handle read %s [%d,%d] %d : %v", fileFullPath, offset, offset+int64(totalRead), totalRead, err)
  123. return int64(totalRead), err
  124. }
  125. // Write to the file handle
  126. func (fh *FileHandle) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {
  127. fh.Lock()
  128. defer fh.Unlock()
  129. // write the request to volume servers
  130. data := req.Data
  131. if len(data) <= 512 {
  132. // fuse message cacheable size
  133. data = make([]byte, len(req.Data))
  134. copy(data, req.Data)
  135. }
  136. entry := fh.f.getEntry()
  137. if entry == nil {
  138. return fuse.EIO
  139. }
  140. entry.Content = nil
  141. entry.Attributes.FileSize = uint64(max(req.Offset+int64(len(data)), int64(entry.Attributes.FileSize)))
  142. glog.V(4).Infof("%v write [%d,%d) %d", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)), len(req.Data))
  143. fh.dirtyPages.AddPage(req.Offset, data)
  144. resp.Size = len(data)
  145. if req.Offset == 0 {
  146. // detect mime type
  147. fh.contentType = http.DetectContentType(data)
  148. fh.f.dirtyMetadata = true
  149. }
  150. fh.f.dirtyMetadata = true
  151. return nil
  152. }
  153. func (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
  154. glog.V(4).Infof("Release %v fh %d open=%d", fh.f.fullpath(), fh.handle, fh.f.isOpen)
  155. fh.Lock()
  156. defer fh.Unlock()
  157. fh.f.isOpen--
  158. if fh.f.isOpen <= 0 {
  159. fh.f.entry = nil
  160. fh.entryViewCache = nil
  161. fh.reader = nil
  162. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  163. }
  164. if fh.f.isOpen < 0 {
  165. glog.V(0).Infof("Release reset %s open count %d => %d", fh.f.Name, fh.f.isOpen, 0)
  166. fh.f.isOpen = 0
  167. return nil
  168. }
  169. return nil
  170. }
  171. func (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {
  172. glog.V(4).Infof("Flush %v fh %d", fh.f.fullpath(), fh.handle)
  173. fh.Lock()
  174. defer fh.Unlock()
  175. if err := fh.doFlush(ctx, req.Header); err != nil {
  176. glog.Errorf("Flush doFlush %s: %v", fh.f.Name, err)
  177. return err
  178. }
  179. glog.V(4).Infof("Flush %v fh %d success", fh.f.fullpath(), fh.handle)
  180. return nil
  181. }
  182. func (fh *FileHandle) doFlush(ctx context.Context, header fuse.Header) error {
  183. // flush works at fh level
  184. // send the data to the OS
  185. glog.V(4).Infof("doFlush %s fh %d", fh.f.fullpath(), fh.handle)
  186. if err := fh.dirtyPages.FlushData(); err != nil {
  187. glog.Errorf("%v doFlush: %v", fh.f.fullpath(), err)
  188. return fuse.EIO
  189. }
  190. if !fh.f.dirtyMetadata {
  191. return nil
  192. }
  193. err := fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  194. entry := fh.f.getEntry()
  195. if entry == nil {
  196. return nil
  197. }
  198. if entry.Attributes != nil {
  199. entry.Attributes.Mime = fh.contentType
  200. if entry.Attributes.Uid == 0 {
  201. entry.Attributes.Uid = header.Uid
  202. }
  203. if entry.Attributes.Gid == 0 {
  204. entry.Attributes.Gid = header.Gid
  205. }
  206. if entry.Attributes.Crtime == 0 {
  207. entry.Attributes.Crtime = time.Now().Unix()
  208. }
  209. entry.Attributes.Mtime = time.Now().Unix()
  210. entry.Attributes.FileMode = uint32(os.FileMode(entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)
  211. entry.Attributes.Collection, entry.Attributes.Replication = fh.dirtyPages.GetStorageOptions()
  212. }
  213. request := &filer_pb.CreateEntryRequest{
  214. Directory: fh.f.dir.FullPath(),
  215. Entry: entry,
  216. Signatures: []int32{fh.f.wfs.signature},
  217. }
  218. glog.V(4).Infof("%s set chunks: %v", fh.f.fullpath(), len(entry.Chunks))
  219. for i, chunk := range entry.Chunks {
  220. glog.V(4).Infof("%s chunks %d: %v [%d,%d)", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))
  221. }
  222. manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(entry.Chunks)
  223. chunks, _ := filer.CompactFileChunks(fh.f.wfs.LookupFn(), nonManifestChunks)
  224. chunks, manifestErr := filer.MaybeManifestize(fh.f.wfs.saveDataAsChunk(fh.f.fullpath(), fh.dirtyPages.GetWriteOnly()), chunks)
  225. if manifestErr != nil {
  226. // not good, but should be ok
  227. glog.V(0).Infof("MaybeManifestize: %v", manifestErr)
  228. }
  229. entry.Chunks = append(chunks, manifestChunks...)
  230. fh.f.wfs.mapPbIdFromLocalToFiler(request.Entry)
  231. defer fh.f.wfs.mapPbIdFromFilerToLocal(request.Entry)
  232. if err := filer_pb.CreateEntry(client, request); err != nil {
  233. glog.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  234. return fmt.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  235. }
  236. fh.f.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  237. return nil
  238. })
  239. if err == nil {
  240. fh.f.dirtyMetadata = false
  241. }
  242. if err != nil {
  243. glog.Errorf("%v fh %d flush: %v", fh.f.fullpath(), fh.handle, err)
  244. return fuse.EIO
  245. }
  246. return nil
  247. }