disk_file.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package backend
  2. import (
  3. "github.com/seaweedfs/seaweedfs/weed/glog"
  4. . "github.com/seaweedfs/seaweedfs/weed/storage/types"
  5. "os"
  6. "runtime"
  7. "time"
  8. )
  9. var (
  10. _ BackendStorageFile = &DiskFile{}
  11. )
  12. const isMac = runtime.GOOS == "darwin"
  13. type DiskFile struct {
  14. File *os.File
  15. fullFilePath string
  16. fileSize int64
  17. modTime time.Time
  18. }
  19. func NewDiskFile(f *os.File) *DiskFile {
  20. stat, err := f.Stat()
  21. if err != nil {
  22. glog.Fatalf("stat file %s: %v", f.Name(), err)
  23. }
  24. offset := stat.Size()
  25. if offset%NeedlePaddingSize != 0 {
  26. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  27. }
  28. return &DiskFile{
  29. fullFilePath: f.Name(),
  30. File: f,
  31. fileSize: offset,
  32. modTime: stat.ModTime(),
  33. }
  34. }
  35. func (df *DiskFile) ReadAt(p []byte, off int64) (n int, err error) {
  36. if df.File == nil {
  37. return 0, os.ErrClosed
  38. }
  39. return df.File.ReadAt(p, off)
  40. }
  41. func (df *DiskFile) WriteAt(p []byte, off int64) (n int, err error) {
  42. if df.File == nil {
  43. return 0, os.ErrClosed
  44. }
  45. n, err = df.File.WriteAt(p, off)
  46. if err == nil {
  47. waterMark := off + int64(n)
  48. if waterMark > df.fileSize {
  49. df.fileSize = waterMark
  50. df.modTime = time.Now()
  51. }
  52. }
  53. return
  54. }
  55. func (df *DiskFile) Write(p []byte) (n int, err error) {
  56. return df.WriteAt(p, df.fileSize)
  57. }
  58. func (df *DiskFile) Truncate(off int64) error {
  59. if df.File == nil {
  60. return os.ErrClosed
  61. }
  62. err := df.File.Truncate(off)
  63. if err == nil {
  64. df.fileSize = off
  65. df.modTime = time.Now()
  66. }
  67. return err
  68. }
  69. func (df *DiskFile) Close() error {
  70. if df.File == nil {
  71. return nil
  72. }
  73. if err := df.Sync(); err != nil {
  74. return err
  75. }
  76. if err := df.File.Close(); err != nil {
  77. return err
  78. }
  79. df.File = nil
  80. return nil
  81. }
  82. func (df *DiskFile) GetStat() (datSize int64, modTime time.Time, err error) {
  83. if df.File == nil {
  84. err = os.ErrClosed
  85. }
  86. return df.fileSize, df.modTime, err
  87. }
  88. func (df *DiskFile) Name() string {
  89. return df.fullFilePath
  90. }
  91. func (df *DiskFile) Sync() error {
  92. if df.File == nil {
  93. return os.ErrClosed
  94. }
  95. if isMac {
  96. return nil
  97. }
  98. return df.File.Sync()
  99. }