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.

348 lines
8.9 KiB

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