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
4 years ago
7 years ago
4 years ago
7 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 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 DirtyPages
  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, writeOnly bool) *FileHandle {
  34. fh := &FileHandle{
  35. f: file,
  36. // dirtyPages: newContinuousDirtyPages(file, writeOnly),
  37. dirtyPages: newTempFileDirtyPages(file, writeOnly),
  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. 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. fh.Lock()
  56. defer fh.Unlock()
  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.Lock()
  139. defer fh.Unlock()
  140. // write the request to volume servers
  141. data := req.Data
  142. if len(data) <= 512 {
  143. // fuse message cacheable size
  144. data = make([]byte, len(req.Data))
  145. copy(data, req.Data)
  146. }
  147. entry := fh.f.getEntry()
  148. if entry == nil {
  149. return fuse.EIO
  150. }
  151. entry.Content = nil
  152. entry.Attributes.FileSize = uint64(max(req.Offset+int64(len(data)), int64(entry.Attributes.FileSize)))
  153. // glog.V(4).Infof("%v write [%d,%d) %d", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)), len(req.Data))
  154. fh.dirtyPages.AddPage(req.Offset, data)
  155. resp.Size = len(data)
  156. if req.Offset == 0 {
  157. // detect mime type
  158. fh.contentType = http.DetectContentType(data)
  159. fh.f.dirtyMetadata = true
  160. }
  161. fh.f.dirtyMetadata = true
  162. return nil
  163. }
  164. func (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
  165. glog.V(4).Infof("Release %v fh %d open=%d", fh.f.fullpath(), fh.handle, fh.f.isOpen)
  166. fh.Lock()
  167. defer fh.Unlock()
  168. fh.f.wfs.handlesLock.Lock()
  169. fh.f.isOpen--
  170. fh.f.wfs.handlesLock.Unlock()
  171. if fh.f.isOpen <= 0 {
  172. fh.f.entry = nil
  173. fh.entryViewCache = nil
  174. fh.reader = nil
  175. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  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. glog.V(4).Infof("Flush %v fh %d success", fh.f.fullpath(), fh.handle)
  197. return nil
  198. }
  199. func (fh *FileHandle) doFlush(ctx context.Context, header fuse.Header) error {
  200. // flush works at fh level
  201. // send the data to the OS
  202. glog.V(4).Infof("doFlush %s fh %d", fh.f.fullpath(), fh.handle)
  203. if err := fh.dirtyPages.FlushData(); err != nil {
  204. glog.Errorf("%v doFlush: %v", fh.f.fullpath(), err)
  205. return fuse.EIO
  206. }
  207. if !fh.f.dirtyMetadata {
  208. return nil
  209. }
  210. err := fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  211. entry := fh.f.getEntry()
  212. if entry == nil {
  213. return nil
  214. }
  215. if entry.Attributes != nil {
  216. entry.Attributes.Mime = fh.contentType
  217. if entry.Attributes.Uid == 0 {
  218. entry.Attributes.Uid = header.Uid
  219. }
  220. if entry.Attributes.Gid == 0 {
  221. entry.Attributes.Gid = header.Gid
  222. }
  223. if entry.Attributes.Crtime == 0 {
  224. entry.Attributes.Crtime = time.Now().Unix()
  225. }
  226. entry.Attributes.Mtime = time.Now().Unix()
  227. entry.Attributes.FileMode = uint32(os.FileMode(entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)
  228. entry.Attributes.Collection, entry.Attributes.Replication = fh.dirtyPages.GetStorageOptions()
  229. }
  230. request := &filer_pb.CreateEntryRequest{
  231. Directory: fh.f.dir.FullPath(),
  232. Entry: entry,
  233. Signatures: []int32{fh.f.wfs.signature},
  234. }
  235. glog.V(4).Infof("%s set chunks: %v", fh.f.fullpath(), len(entry.Chunks))
  236. for i, chunk := range entry.Chunks {
  237. glog.V(4).Infof("%s chunks %d: %v [%d,%d)", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))
  238. }
  239. manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(entry.Chunks)
  240. chunks, _ := filer.CompactFileChunks(fh.f.wfs.LookupFn(), nonManifestChunks)
  241. chunks, manifestErr := filer.MaybeManifestize(fh.f.wfs.saveDataAsChunk(fh.f.fullpath(), fh.dirtyPages.GetWriteOnly()), chunks)
  242. if manifestErr != nil {
  243. // not good, but should be ok
  244. glog.V(0).Infof("MaybeManifestize: %v", manifestErr)
  245. }
  246. entry.Chunks = append(chunks, manifestChunks...)
  247. fh.f.wfs.mapPbIdFromLocalToFiler(request.Entry)
  248. defer fh.f.wfs.mapPbIdFromFilerToLocal(request.Entry)
  249. if err := filer_pb.CreateEntry(client, request); err != nil {
  250. glog.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  251. return fmt.Errorf("fh flush create %s: %v", fh.f.fullpath(), err)
  252. }
  253. fh.f.wfs.metaCache.InsertEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry))
  254. return nil
  255. })
  256. if err == nil {
  257. fh.f.dirtyMetadata = false
  258. }
  259. if err != nil {
  260. glog.Errorf("%v fh %d flush: %v", fh.f.fullpath(), fh.handle, err)
  261. return fuse.EIO
  262. }
  263. return nil
  264. }