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.

324 lines
8.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
4 years ago
6 years ago
5 years ago
4 years ago
6 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 *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. fh.f.entryViewCache = nil
  158. if fh.f.isOpen <= 0 {
  159. glog.V(0).Infof("Release reset %s open count %d => %d", fh.f.Name, fh.f.isOpen, 0)
  160. fh.f.isOpen = 0
  161. return nil
  162. }
  163. if fh.f.isOpen == 1 {
  164. fh.f.isOpen--
  165. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  166. fh.f.setReader(nil)
  167. }
  168. return nil
  169. }
  170. func (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {
  171. glog.V(4).Infof("Flush %v fh %d", fh.f.fullpath(), fh.handle)
  172. fh.Lock()
  173. defer fh.Unlock()
  174. if err := fh.doFlush(ctx, req.Header); err != nil {
  175. glog.Errorf("Flush doFlush %s: %v", fh.f.Name, err)
  176. return err
  177. }
  178. glog.V(4).Infof("Flush %v fh %d success", fh.f.fullpath(), fh.handle)
  179. return nil
  180. }
  181. func (fh *FileHandle) doFlush(ctx context.Context, header fuse.Header) error {
  182. // flush works at fh level
  183. // send the data to the OS
  184. glog.V(4).Infof("doFlush %s fh %d", fh.f.fullpath(), fh.handle)
  185. fh.dirtyPages.saveExistingPagesToStorage()
  186. fh.dirtyPages.writeWaitGroup.Wait()
  187. if fh.dirtyPages.lastErr != nil {
  188. glog.Errorf("%v doFlush last err: %v", fh.f.fullpath(), fh.dirtyPages.lastErr)
  189. return fuse.EIO
  190. }
  191. if !fh.f.dirtyMetadata {
  192. return nil
  193. }
  194. err := fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  195. entry := fh.f.getEntry()
  196. if entry == nil {
  197. return nil
  198. }
  199. if entry.Attributes != nil {
  200. entry.Attributes.Mime = fh.contentType
  201. if entry.Attributes.Uid == 0 {
  202. entry.Attributes.Uid = header.Uid
  203. }
  204. if entry.Attributes.Gid == 0 {
  205. entry.Attributes.Gid = header.Gid
  206. }
  207. if entry.Attributes.Crtime == 0 {
  208. entry.Attributes.Crtime = time.Now().Unix()
  209. }
  210. entry.Attributes.Mtime = time.Now().Unix()
  211. entry.Attributes.FileMode = uint32(os.FileMode(entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)
  212. entry.Attributes.Collection = fh.dirtyPages.collection
  213. entry.Attributes.Replication = fh.dirtyPages.replication
  214. }
  215. request := &filer_pb.CreateEntryRequest{
  216. Directory: fh.f.dir.FullPath(),
  217. Entry: entry,
  218. Signatures: []int32{fh.f.wfs.signature},
  219. }
  220. glog.V(4).Infof("%s set chunks: %v", fh.f.fullpath(), len(entry.Chunks))
  221. for i, chunk := range entry.Chunks {
  222. glog.V(4).Infof("%s chunks %d: %v [%d,%d)", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))
  223. }
  224. manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(entry.Chunks)
  225. chunks, _ := filer.CompactFileChunks(fh.f.wfs.LookupFn(), nonManifestChunks)
  226. chunks, manifestErr := filer.MaybeManifestize(fh.f.wfs.saveDataAsChunk(fh.f.fullpath()), chunks)
  227. if manifestErr != nil {
  228. // not good, but should be ok
  229. glog.V(0).Infof("MaybeManifestize: %v", manifestErr)
  230. }
  231. entry.Chunks = append(chunks, manifestChunks...)
  232. fh.f.wfs.mapPbIdFromLocalToFiler(request.Entry)
  233. defer fh.f.wfs.mapPbIdFromFilerToLocal(request.Entry)
  234. if err := filer_pb.CreateEntry(client, request); err != nil {
  235. glog.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  236. return fmt.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  237. }
  238. fh.f.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  239. return nil
  240. })
  241. if err == nil {
  242. fh.f.dirtyMetadata = false
  243. }
  244. if err != nil {
  245. glog.Errorf("%v fh %d flush: %v", fh.f.fullpath(), fh.handle, err)
  246. return fuse.EIO
  247. }
  248. return nil
  249. }