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.

281 lines
7.5 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
  1. package filesys
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer2"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/operation"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. "github.com/seaweedfs/fuse"
  11. "github.com/seaweedfs/fuse/fs"
  12. "net/http"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. type FileHandle struct {
  18. // cache file has been written to
  19. dirtyPages *ContinuousDirtyPages
  20. contentType string
  21. dirtyMetadata bool
  22. handle uint64
  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. return &FileHandle{
  31. f: file,
  32. dirtyPages: newDirtyPages(file),
  33. Uid: uid,
  34. Gid: gid,
  35. }
  36. }
  37. var _ = fs.Handle(&FileHandle{})
  38. // var _ = fs.HandleReadAller(&FileHandle{})
  39. var _ = fs.HandleReader(&FileHandle{})
  40. var _ = fs.HandleFlusher(&FileHandle{})
  41. var _ = fs.HandleWriter(&FileHandle{})
  42. var _ = fs.HandleReleaser(&FileHandle{})
  43. func (fh *FileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
  44. glog.V(4).Infof("%s read fh %d: [%d,%d)", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(req.Size))
  45. // this value should come from the filer instead of the old f
  46. if len(fh.f.entry.Chunks) == 0 {
  47. glog.V(1).Infof("empty fh %v/%v", fh.f.dir.Path, fh.f.Name)
  48. return nil
  49. }
  50. buff := make([]byte, req.Size)
  51. if fh.f.entryViewCache == nil {
  52. fh.f.entryViewCache = filer2.NonOverlappingVisibleIntervals(fh.f.entry.Chunks)
  53. }
  54. chunkViews := filer2.ViewFromVisibleIntervals(fh.f.entryViewCache, req.Offset, req.Size)
  55. var vids []string
  56. for _, chunkView := range chunkViews {
  57. vids = append(vids, volumeId(chunkView.FileId))
  58. }
  59. vid2Locations := make(map[string]*filer_pb.Locations)
  60. err := fh.f.wfs.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  61. glog.V(4).Infof("read fh lookup volume id locations: %v", vids)
  62. resp, err := client.LookupVolume(ctx, &filer_pb.LookupVolumeRequest{
  63. VolumeIds: vids,
  64. })
  65. if err != nil {
  66. return err
  67. }
  68. vid2Locations = resp.LocationsMap
  69. return nil
  70. })
  71. if err != nil {
  72. glog.V(4).Infof("%v/%v read fh lookup volume ids: %v", fh.f.dir.Path, fh.f.Name, err)
  73. return fmt.Errorf("failed to lookup volume ids %v: %v", vids, err)
  74. }
  75. var totalRead int64
  76. var wg sync.WaitGroup
  77. for _, chunkView := range chunkViews {
  78. wg.Add(1)
  79. go func(chunkView *filer2.ChunkView) {
  80. defer wg.Done()
  81. glog.V(4).Infof("read fh reading chunk: %+v", chunkView)
  82. locations := vid2Locations[volumeId(chunkView.FileId)]
  83. if locations == nil || len(locations.Locations) == 0 {
  84. glog.V(0).Infof("failed to locate %s", chunkView.FileId)
  85. err = fmt.Errorf("failed to locate %s", chunkView.FileId)
  86. return
  87. }
  88. var n int64
  89. n, err = util.ReadUrl(
  90. fmt.Sprintf("http://%s/%s", locations.Locations[0].Url, chunkView.FileId),
  91. chunkView.Offset,
  92. int(chunkView.Size),
  93. buff[chunkView.LogicOffset-req.Offset:chunkView.LogicOffset-req.Offset+int64(chunkView.Size)],
  94. !chunkView.IsFullChunk)
  95. if err != nil {
  96. glog.V(0).Infof("%v/%v read http://%s/%v %v bytes: %v", fh.f.dir.Path, fh.f.Name, locations.Locations[0].Url, chunkView.FileId, n, err)
  97. err = fmt.Errorf("failed to read http://%s/%s: %v",
  98. locations.Locations[0].Url, chunkView.FileId, err)
  99. return
  100. }
  101. glog.V(4).Infof("read fh read %d bytes: %+v", n, chunkView)
  102. totalRead += n
  103. }(chunkView)
  104. }
  105. wg.Wait()
  106. resp.Data = buff[:totalRead]
  107. return err
  108. }
  109. // Write to the file handle
  110. func (fh *FileHandle) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {
  111. // write the request to volume servers
  112. glog.V(4).Infof("%+v/%v write fh %d: [%d,%d)", fh.f.dir.Path, fh.f.Name, fh.handle, req.Offset, req.Offset+int64(len(req.Data)))
  113. chunks, err := fh.dirtyPages.AddPage(ctx, req.Offset, req.Data)
  114. if err != nil {
  115. glog.Errorf("%+v/%v write fh %d: [%d,%d): %v", fh.f.dir.Path, fh.f.Name, fh.handle, req.Offset, req.Offset+int64(len(req.Data)), err)
  116. return fmt.Errorf("write %s/%s at [%d,%d): %v", fh.f.dir.Path, fh.f.Name, req.Offset, req.Offset+int64(len(req.Data)), err)
  117. }
  118. resp.Size = len(req.Data)
  119. if req.Offset == 0 {
  120. fh.contentType = http.DetectContentType(req.Data)
  121. fh.dirtyMetadata = true
  122. }
  123. fh.f.addChunks(chunks)
  124. if len(chunks) > 0 {
  125. fh.dirtyMetadata = true
  126. }
  127. return nil
  128. }
  129. func (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
  130. glog.V(4).Infof("%v release fh %d", fh.f.fullpath(), fh.handle)
  131. fh.dirtyPages.releaseResource()
  132. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  133. fh.f.isOpen = false
  134. return nil
  135. }
  136. func (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {
  137. // fflush works at fh level
  138. // send the data to the OS
  139. glog.V(4).Infof("%s fh %d flush %v", fh.f.fullpath(), fh.handle, req)
  140. chunk, err := fh.dirtyPages.FlushToStorage(ctx)
  141. if err != nil {
  142. glog.Errorf("flush %s/%s: %v", fh.f.dir.Path, fh.f.Name, err)
  143. return fmt.Errorf("flush %s/%s: %v", fh.f.dir.Path, fh.f.Name, err)
  144. }
  145. fh.f.addChunk(chunk)
  146. if !fh.dirtyMetadata {
  147. return nil
  148. }
  149. return fh.f.wfs.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  150. if fh.f.entry.Attributes != nil {
  151. fh.f.entry.Attributes.Mime = fh.contentType
  152. fh.f.entry.Attributes.Uid = req.Uid
  153. fh.f.entry.Attributes.Gid = req.Gid
  154. fh.f.entry.Attributes.Mtime = time.Now().Unix()
  155. fh.f.entry.Attributes.Crtime = time.Now().Unix()
  156. fh.f.entry.Attributes.FileMode = uint32(0770)
  157. }
  158. request := &filer_pb.CreateEntryRequest{
  159. Directory: fh.f.dir.Path,
  160. Entry: fh.f.entry,
  161. }
  162. //glog.V(1).Infof("%s/%s set chunks: %v", fh.f.dir.Path, fh.f.Name, len(fh.f.entry.Chunks))
  163. //for i, chunk := range fh.f.entry.Chunks {
  164. // glog.V(4).Infof("%s/%s chunks %d: %v [%d,%d)", fh.f.dir.Path, fh.f.Name, i, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
  165. //}
  166. chunks, garbages := filer2.CompactFileChunks(fh.f.entry.Chunks)
  167. fh.f.entry.Chunks = chunks
  168. // fh.f.entryViewCache = nil
  169. fh.f.wfs.asyncDeleteFileChunks(garbages)
  170. if _, err := client.CreateEntry(ctx, request); err != nil {
  171. return fmt.Errorf("update fh: %v", err)
  172. }
  173. return nil
  174. })
  175. }
  176. func deleteFileIds(ctx context.Context, client filer_pb.SeaweedFilerClient, fileIds []string) error {
  177. var vids []string
  178. for _, fileId := range fileIds {
  179. vids = append(vids, volumeId(fileId))
  180. }
  181. lookupFunc := func(vids []string) (map[string]operation.LookupResult, error) {
  182. m := make(map[string]operation.LookupResult)
  183. glog.V(4).Infof("remove file lookup volume id locations: %v", vids)
  184. resp, err := client.LookupVolume(ctx, &filer_pb.LookupVolumeRequest{
  185. VolumeIds: vids,
  186. })
  187. if err != nil {
  188. return m, err
  189. }
  190. for _, vid := range vids {
  191. lr := operation.LookupResult{
  192. VolumeId: vid,
  193. Locations: nil,
  194. }
  195. locations := resp.LocationsMap[vid]
  196. for _, loc := range locations.Locations {
  197. lr.Locations = append(lr.Locations, operation.Location{
  198. Url: loc.Url,
  199. PublicUrl: loc.PublicUrl,
  200. })
  201. }
  202. m[vid] = lr
  203. }
  204. return m, err
  205. }
  206. _, err := operation.DeleteFilesWithLookupVolumeId(fileIds, lookupFunc)
  207. return err
  208. }
  209. func volumeId(fileId string) string {
  210. lastCommaIndex := strings.LastIndex(fileId, ",")
  211. if lastCommaIndex > 0 {
  212. return fileId[:lastCommaIndex]
  213. }
  214. return fileId
  215. }