filehandle.go 9.4 KB

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