filehandle.go 9.3 KB

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