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.

334 lines
8.7 KiB

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