disk_file.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package backend
  2. import (
  3. "github.com/chrislusf/seaweedfs/weed/glog"
  4. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  5. "os"
  6. "time"
  7. )
  8. var (
  9. _ BackendStorageFile = &DiskFile{}
  10. )
  11. type DiskFile struct {
  12. File *os.File
  13. fullFilePath string
  14. fileSize int64
  15. modTime time.Time
  16. }
  17. func NewDiskFile(f *os.File) *DiskFile {
  18. stat, err := f.Stat()
  19. if err != nil {
  20. glog.Fatalf("stat file %s: %v", f.Name(), err)
  21. }
  22. offset := stat.Size()
  23. if offset%NeedlePaddingSize != 0 {
  24. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  25. }
  26. return &DiskFile{
  27. fullFilePath: f.Name(),
  28. File: f,
  29. fileSize: offset,
  30. modTime: stat.ModTime(),
  31. }
  32. }
  33. func (df *DiskFile) ReadAt(p []byte, off int64) (n int, err error) {
  34. return df.File.ReadAt(p, off)
  35. }
  36. func (df *DiskFile) WriteAt(p []byte, off int64) (n int, err error) {
  37. n, err = df.File.WriteAt(p, off)
  38. if err == nil {
  39. waterMark := off + int64(n)
  40. if waterMark > df.fileSize {
  41. df.fileSize = waterMark
  42. df.modTime = time.Now()
  43. }
  44. }
  45. return
  46. }
  47. func (df *DiskFile) Write(p []byte) (n int, err error) {
  48. return df.WriteAt(p, df.fileSize)
  49. }
  50. func (df *DiskFile) Truncate(off int64) error {
  51. err := df.File.Truncate(off)
  52. if err == nil {
  53. df.fileSize = off
  54. df.modTime = time.Now()
  55. }
  56. return err
  57. }
  58. func (df *DiskFile) Close() error {
  59. return df.File.Close()
  60. }
  61. func (df *DiskFile) GetStat() (datSize int64, modTime time.Time, err error) {
  62. return df.fileSize, df.modTime, nil
  63. }
  64. func (df *DiskFile) Name() string {
  65. return df.fullFilePath
  66. }
  67. func (df *DiskFile) Sync() error {
  68. return df.File.Sync()
  69. }