filehandle.go 8.1 KB

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