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.

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