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.2 KiB

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