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.

322 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. if fh.f.wfs.option.ReadOnly {
  125. return fuse.EPERM
  126. }
  127. fh.Lock()
  128. defer fh.Unlock()
  129. // write the request to volume servers
  130. data := req.Data
  131. if len(data) <= 512 {
  132. // fuse message cacheable size
  133. data = make([]byte, len(req.Data))
  134. copy(data, req.Data)
  135. }
  136. entry := fh.f.getEntry()
  137. if entry == nil {
  138. return fuse.EIO
  139. }
  140. entry.Content = nil
  141. entry.Attributes.FileSize = uint64(max(req.Offset+int64(len(data)), int64(entry.Attributes.FileSize)))
  142. glog.V(4).Infof("%v write [%d,%d) %d", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)), len(req.Data))
  143. fh.dirtyPages.AddPage(req.Offset, data)
  144. resp.Size = len(data)
  145. if req.Offset == 0 {
  146. // detect mime type
  147. fh.contentType = http.DetectContentType(data)
  148. fh.f.dirtyMetadata = true
  149. }
  150. fh.f.dirtyMetadata = true
  151. return nil
  152. }
  153. func (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
  154. glog.V(4).Infof("Release %v fh %d", fh.f.fullpath(), fh.handle)
  155. fh.Lock()
  156. defer fh.Unlock()
  157. if fh.f.isOpen <= 0 {
  158. glog.V(0).Infof("Release reset %s open count %d => %d", fh.f.Name, fh.f.isOpen, 0)
  159. fh.f.isOpen = 0
  160. return nil
  161. }
  162. if fh.f.isOpen == 1 {
  163. fh.f.isOpen--
  164. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  165. fh.f.setReader(nil)
  166. }
  167. return nil
  168. }
  169. func (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {
  170. glog.V(4).Infof("Flush %v fh %d", fh.f.fullpath(), fh.handle)
  171. fh.Lock()
  172. defer fh.Unlock()
  173. if err := fh.doFlush(ctx, req.Header); err != nil {
  174. glog.Errorf("Flush doFlush %s: %v", fh.f.Name, err)
  175. return err
  176. }
  177. glog.V(4).Infof("Flush %v fh %d success", fh.f.fullpath(), fh.handle)
  178. return nil
  179. }
  180. func (fh *FileHandle) doFlush(ctx context.Context, header fuse.Header) error {
  181. // flush works at fh level
  182. // send the data to the OS
  183. glog.V(4).Infof("doFlush %s fh %d", fh.f.fullpath(), fh.handle)
  184. fh.dirtyPages.saveExistingPagesToStorage()
  185. fh.dirtyPages.writeWaitGroup.Wait()
  186. if fh.dirtyPages.lastErr != nil {
  187. glog.Errorf("%v doFlush last err: %v", fh.f.fullpath(), fh.dirtyPages.lastErr)
  188. return fuse.EIO
  189. }
  190. if !fh.f.dirtyMetadata {
  191. return nil
  192. }
  193. err := fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  194. entry := fh.f.getEntry()
  195. if entry == nil {
  196. return nil
  197. }
  198. if entry.Attributes != nil {
  199. entry.Attributes.Mime = fh.contentType
  200. if entry.Attributes.Uid == 0 {
  201. entry.Attributes.Uid = header.Uid
  202. }
  203. if entry.Attributes.Gid == 0 {
  204. entry.Attributes.Gid = header.Gid
  205. }
  206. if entry.Attributes.Crtime == 0 {
  207. entry.Attributes.Crtime = time.Now().Unix()
  208. }
  209. entry.Attributes.Mtime = time.Now().Unix()
  210. entry.Attributes.FileMode = uint32(os.FileMode(entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)
  211. entry.Attributes.Collection = fh.dirtyPages.collection
  212. entry.Attributes.Replication = fh.dirtyPages.replication
  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()), 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. }