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
9.0 KiB

7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
3 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 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. Uid: uid,
  35. Gid: gid,
  36. }
  37. // dirtyPages: newContinuousDirtyPages(file, writeOnly),
  38. fh.dirtyPages = newPageWriter(fh, file.wfs.option.ChunkSizeLimit)
  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. glog.V(4).Infof("file handle read %s [%d,%d) from %+v", fileFullPath, offset, offset+int64(len(buff)), chunkViews)
  125. for _, chunkView := range chunkViews {
  126. glog.V(4).Infof(" read %s [%d,%d) from chunk %+v", fileFullPath, chunkView.LogicOffset, chunkView.LogicOffset+int64(chunkView.Size), chunkView.FileId)
  127. }
  128. reader = filer.NewChunkReaderAtFromClient(fh.f.wfs.LookupFn(), chunkViews, fh.f.wfs.chunkCache, fileSize)
  129. }
  130. fh.reader = reader
  131. totalRead, err := reader.ReadAt(buff, offset)
  132. if err != nil && err != io.EOF {
  133. glog.Errorf("file handle read %s: %v", fileFullPath, err)
  134. }
  135. // glog.V(4).Infof("file handle read %s [%d,%d] %d : %v", fileFullPath, offset, offset+int64(totalRead), totalRead, err)
  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. }