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.

284 lines
7.8 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
7 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. for _, chunk := range chunks {
  124. fh.f.entry.Chunks = append(fh.f.entry.Chunks, chunk)
  125. fh.f.entryViewCache = nil
  126. glog.V(4).Infof("uploaded %s/%s to %s [%d,%d)", fh.f.dir.Path, fh.f.Name, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
  127. fh.dirtyMetadata = true
  128. }
  129. return nil
  130. }
  131. func (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
  132. glog.V(4).Infof("%v release fh %d", fh.f.fullpath(), fh.handle)
  133. fh.dirtyPages.releaseResource()
  134. fh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))
  135. fh.f.isOpen = false
  136. return nil
  137. }
  138. func (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {
  139. // fflush works at fh level
  140. // send the data to the OS
  141. glog.V(4).Infof("%s fh %d flush %v", fh.f.fullpath(), fh.handle, req)
  142. chunk, err := fh.dirtyPages.FlushToStorage(ctx)
  143. if err != nil {
  144. glog.Errorf("flush %s/%s: %v", fh.f.dir.Path, fh.f.Name, err)
  145. return fmt.Errorf("flush %s/%s: %v", fh.f.dir.Path, fh.f.Name, err)
  146. }
  147. if chunk != nil {
  148. fh.f.entry.Chunks = append(fh.f.entry.Chunks, chunk)
  149. fh.f.entryViewCache = nil
  150. }
  151. if !fh.dirtyMetadata {
  152. return nil
  153. }
  154. return fh.f.wfs.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  155. if fh.f.entry.Attributes != nil {
  156. fh.f.entry.Attributes.Mime = fh.contentType
  157. fh.f.entry.Attributes.Uid = req.Uid
  158. fh.f.entry.Attributes.Gid = req.Gid
  159. fh.f.entry.Attributes.Mtime = time.Now().Unix()
  160. fh.f.entry.Attributes.Crtime = time.Now().Unix()
  161. fh.f.entry.Attributes.FileMode = uint32(0770)
  162. }
  163. request := &filer_pb.CreateEntryRequest{
  164. Directory: fh.f.dir.Path,
  165. Entry: fh.f.entry,
  166. }
  167. //glog.V(1).Infof("%s/%s set chunks: %v", fh.f.dir.Path, fh.f.Name, len(fh.f.entry.Chunks))
  168. //for i, chunk := range fh.f.entry.Chunks {
  169. // 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))
  170. //}
  171. chunks, garbages := filer2.CompactFileChunks(fh.f.entry.Chunks)
  172. fh.f.entry.Chunks = chunks
  173. fh.f.entryViewCache = nil
  174. fh.f.wfs.asyncDeleteFileChunks(garbages)
  175. if _, err := client.CreateEntry(ctx, request); err != nil {
  176. return fmt.Errorf("update fh: %v", err)
  177. }
  178. return nil
  179. })
  180. }
  181. func deleteFileIds(ctx context.Context, client filer_pb.SeaweedFilerClient, fileIds []string) error {
  182. var vids []string
  183. for _, fileId := range fileIds {
  184. vids = append(vids, volumeId(fileId))
  185. }
  186. lookupFunc := func(vids []string) (map[string]operation.LookupResult, error) {
  187. m := make(map[string]operation.LookupResult)
  188. glog.V(4).Infof("remove file lookup volume id locations: %v", vids)
  189. resp, err := client.LookupVolume(ctx, &filer_pb.LookupVolumeRequest{
  190. VolumeIds: vids,
  191. })
  192. if err != nil {
  193. return m, err
  194. }
  195. for _, vid := range vids {
  196. lr := operation.LookupResult{
  197. VolumeId: vid,
  198. Locations: nil,
  199. }
  200. locations := resp.LocationsMap[vid]
  201. for _, loc := range locations.Locations {
  202. lr.Locations = append(lr.Locations, operation.Location{
  203. Url: loc.Url,
  204. PublicUrl: loc.PublicUrl,
  205. })
  206. }
  207. m[vid] = lr
  208. }
  209. return m, err
  210. }
  211. _, err := operation.DeleteFilesWithLookupVolumeId(fileIds, lookupFunc)
  212. return err
  213. }
  214. func volumeId(fileId string) string {
  215. lastCommaIndex := strings.LastIndex(fileId, ",")
  216. if lastCommaIndex > 0 {
  217. return fileId[:lastCommaIndex]
  218. }
  219. return fileId
  220. }