disk_file.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. err := df.Sync()
  74. var err1 error
  75. if df.File != nil {
  76. // always try to close
  77. err1 = df.File.Close()
  78. }
  79. // assume closed
  80. df.File = nil
  81. if err != nil {
  82. return err
  83. }
  84. if err1 != nil {
  85. return err1
  86. }
  87. return nil
  88. }
  89. func (df *DiskFile) GetStat() (datSize int64, modTime time.Time, err error) {
  90. if df.File == nil {
  91. err = os.ErrClosed
  92. }
  93. return df.fileSize, df.modTime, err
  94. }
  95. func (df *DiskFile) Name() string {
  96. return df.fullFilePath
  97. }
  98. func (df *DiskFile) Sync() error {
  99. if df.File == nil {
  100. return os.ErrClosed
  101. }
  102. if isMac {
  103. return nil
  104. }
  105. return df.File.Sync()
  106. }