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.

324 lines
8.5 KiB

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