weedfs_file_lseek.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package mount
  2. import (
  3. "context"
  4. "syscall"
  5. "github.com/seaweedfs/seaweedfs/weed/util"
  6. "github.com/hanwen/go-fuse/v2/fuse"
  7. "github.com/seaweedfs/seaweedfs/weed/filer"
  8. "github.com/seaweedfs/seaweedfs/weed/glog"
  9. )
  10. // These are non-POSIX extensions
  11. const (
  12. SEEK_DATA uint32 = 3 // seek to next data after the offset
  13. SEEK_HOLE uint32 = 4 // seek to next hole after the offset
  14. ENXIO = fuse.Status(syscall.ENXIO)
  15. )
  16. // Lseek finds next data or hole segments after the specified offset
  17. // See https://man7.org/linux/man-pages/man2/lseek.2.html
  18. func (wfs *WFS) Lseek(cancel <-chan struct{}, in *fuse.LseekIn, out *fuse.LseekOut) fuse.Status {
  19. // not a documented feature
  20. if in.Padding != 0 {
  21. return fuse.EINVAL
  22. }
  23. if in.Whence != SEEK_DATA && in.Whence != SEEK_HOLE {
  24. return fuse.EINVAL
  25. }
  26. // file must exist
  27. fh := wfs.GetHandle(FileHandleId(in.Fh))
  28. if fh == nil {
  29. return fuse.EBADF
  30. }
  31. // lock the file until the proper offset was calculated
  32. fhActiveLock := fh.wfs.fhLockTable.AcquireLock("Lseek", fh.fh, util.SharedLock)
  33. defer fh.wfs.fhLockTable.ReleaseLock(fh.fh, fhActiveLock)
  34. fileSize := int64(filer.FileSize(fh.GetEntry().GetEntry()))
  35. offset := max(int64(in.Offset), 0)
  36. glog.V(4).Infof(
  37. "Lseek %s fh %d in [%d,%d], whence %d",
  38. fh.FullPath(), fh.fh, offset, fileSize, in.Whence,
  39. )
  40. // can neither seek beyond file nor seek to a hole at the end of the file with SEEK_DATA
  41. if offset > fileSize {
  42. return ENXIO
  43. } else if in.Whence == SEEK_DATA && offset == fileSize {
  44. return ENXIO
  45. }
  46. // Create a context that will be cancelled when the cancel channel receives a signal
  47. ctx, cancelFunc := context.WithCancel(context.Background())
  48. defer cancelFunc() // Ensure cleanup
  49. go func() {
  50. select {
  51. case <-cancel:
  52. cancelFunc()
  53. case <-ctx.Done():
  54. // Clean exit when lseek operation completes
  55. }
  56. }()
  57. // search chunks for the offset
  58. found, offset := fh.entryChunkGroup.SearchChunks(ctx, offset, fileSize, in.Whence)
  59. if found {
  60. out.Offset = uint64(offset)
  61. return fuse.OK
  62. }
  63. // in case we found no exact matches, we return the recommended fallbacks, that is:
  64. // original offset for SEEK_DATA or end of file for an implicit hole
  65. if in.Whence == SEEK_DATA {
  66. out.Offset = in.Offset
  67. } else {
  68. out.Offset = uint64(fileSize)
  69. }
  70. return fuse.OK
  71. }