You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.4 KiB

6 years ago
6 years ago
4 years ago
  1. package storage
  2. import (
  3. "os"
  4. "github.com/chrislusf/seaweedfs/weed/glog"
  5. "github.com/chrislusf/seaweedfs/weed/storage/idx"
  6. "github.com/chrislusf/seaweedfs/weed/storage/needle_map"
  7. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  8. )
  9. type NeedleMap struct {
  10. baseNeedleMapper
  11. m needle_map.NeedleValueMap
  12. }
  13. func NewCompactNeedleMap(file *os.File) *NeedleMap {
  14. nm := &NeedleMap{
  15. m: needle_map.NewCompactMap(),
  16. }
  17. nm.indexFile = file
  18. return nm
  19. }
  20. func LoadCompactNeedleMap(file *os.File) (*NeedleMap, error) {
  21. nm := NewCompactNeedleMap(file)
  22. return doLoading(file, nm)
  23. }
  24. func doLoading(file *os.File, nm *NeedleMap) (*NeedleMap, error) {
  25. e := idx.WalkIndexFile(file, func(key NeedleId, offset Offset, size Size) error {
  26. nm.MaybeSetMaxFileKey(key)
  27. if !offset.IsZero() {
  28. nm.FileCounter++
  29. nm.FileByteCounter = nm.FileByteCounter + uint64(size)
  30. oldOffset, oldSize := nm.m.Set(NeedleId(key), offset, size)
  31. if !oldOffset.IsZero() && oldSize.IsValid() {
  32. nm.DeletionCounter++
  33. nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(oldSize)
  34. } else if size < 0 {
  35. // deletion
  36. nm.DeletionCounter++
  37. nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(-size)
  38. }
  39. } else {
  40. oldSize := nm.m.Delete(NeedleId(key))
  41. nm.DeletionCounter++
  42. nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(oldSize)
  43. }
  44. return nil
  45. })
  46. glog.V(1).Infof("max file key: %d for file: %s", nm.MaxFileKey(), file.Name())
  47. return nm, e
  48. }
  49. func (nm *NeedleMap) Put(key NeedleId, offset Offset, size Size) error {
  50. _, oldSize := nm.m.Set(NeedleId(key), offset, size)
  51. nm.logPut(key, oldSize, size)
  52. return nm.appendToIndexFile(key, offset, size)
  53. }
  54. func (nm *NeedleMap) Get(key NeedleId) (existingValue *needle_map.NeedleValue, ok bool) {
  55. existingValue, ok = nm.m.Get(NeedleId(key))
  56. return
  57. }
  58. func (nm *NeedleMap) Delete(key NeedleId) error {
  59. existingValue, ok := nm.m.Get(NeedleId(key))
  60. if !ok || existingValue.Size.IsDeleted(){
  61. return nil
  62. }
  63. deletedBytes := nm.m.Delete(NeedleId(key))
  64. nm.logDelete(deletedBytes)
  65. return nm.appendToIndexFile(key, existingValue.Offset, -existingValue.Size)
  66. }
  67. func (nm *NeedleMap) Close() {
  68. indexFileName := nm.indexFile.Name()
  69. if err := nm.indexFile.Sync(); err != nil {
  70. glog.Warningf("sync file %s failed, %v", indexFileName, err)
  71. }
  72. _ = nm.indexFile.Close()
  73. }
  74. func (nm *NeedleMap) Destroy() error {
  75. nm.Close()
  76. return os.Remove(nm.indexFile.Name())
  77. }