needle_map.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package storage
  2. import (
  3. "io"
  4. "os"
  5. "sync"
  6. "github.com/seaweedfs/seaweedfs/weed/storage/idx"
  7. "github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
  8. . "github.com/seaweedfs/seaweedfs/weed/storage/types"
  9. "github.com/syndtr/goleveldb/leveldb/opt"
  10. )
  11. type NeedleMapKind int
  12. const (
  13. NeedleMapInMemory NeedleMapKind = iota
  14. NeedleMapLevelDb // small memory footprint, 4MB total, 1 write buffer, 3 block buffer
  15. NeedleMapLevelDbMedium // medium memory footprint, 8MB total, 3 write buffer, 5 block buffer
  16. NeedleMapLevelDbLarge // large memory footprint, 12MB total, 4write buffer, 8 block buffer
  17. )
  18. type NeedleMapper interface {
  19. Put(key NeedleId, offset Offset, size Size) error
  20. Get(key NeedleId) (element *needle_map.NeedleValue, ok bool)
  21. Delete(key NeedleId, offset Offset) error
  22. Close()
  23. Destroy() error
  24. ContentSize() uint64
  25. DeletedSize() uint64
  26. FileCount() int
  27. DeletedCount() int
  28. MaxFileKey() NeedleId
  29. IndexFileSize() uint64
  30. Sync() error
  31. ReadIndexEntry(n int64) (key NeedleId, offset Offset, size Size, err error)
  32. }
  33. type baseNeedleMapper struct {
  34. mapMetric
  35. indexFile *os.File
  36. indexFileAccessLock sync.Mutex
  37. indexFileOffset int64
  38. }
  39. type TempNeedleMapper interface {
  40. NeedleMapper
  41. DoOffsetLoading(v *Volume, indexFile *os.File, startFrom uint64) error
  42. UpdateNeedleMap(v *Volume, indexFile *os.File, opts *opt.Options) error
  43. UpdateNeedleMapMetric(indexFile *os.File) error
  44. }
  45. func (nm *baseNeedleMapper) IndexFileSize() uint64 {
  46. stat, err := nm.indexFile.Stat()
  47. if err == nil {
  48. return uint64(stat.Size())
  49. }
  50. return 0
  51. }
  52. func (nm *baseNeedleMapper) appendToIndexFile(key NeedleId, offset Offset, size Size) error {
  53. bytes := needle_map.ToBytes(key, offset, size)
  54. nm.indexFileAccessLock.Lock()
  55. defer nm.indexFileAccessLock.Unlock()
  56. written, err := nm.indexFile.WriteAt(bytes, nm.indexFileOffset)
  57. if err == nil {
  58. nm.indexFileOffset += int64(written)
  59. }
  60. return err
  61. }
  62. func (nm *baseNeedleMapper) Sync() error {
  63. return nm.indexFile.Sync()
  64. }
  65. func (nm *baseNeedleMapper) ReadIndexEntry(n int64) (key NeedleId, offset Offset, size Size, err error) {
  66. bytes := make([]byte, NeedleMapEntrySize)
  67. var readCount int
  68. if readCount, err = nm.indexFile.ReadAt(bytes, n*NeedleMapEntrySize); err != nil {
  69. if err == io.EOF {
  70. if readCount == NeedleMapEntrySize {
  71. err = nil
  72. }
  73. }
  74. if err != nil {
  75. return
  76. }
  77. }
  78. key, offset, size = idx.IdxFileEntry(bytes)
  79. return
  80. }