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.

306 lines
8.2 KiB

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