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.

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