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.

338 lines
8.9 KiB

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