volume_super_block.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package storage
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/util"
  7. )
  8. const (
  9. SuperBlockSize = 8
  10. )
  11. /*
  12. * Super block currently has 8 bytes allocated for each volume.
  13. * Byte 0: version, 1 or 2
  14. * Byte 1: Replica Placement strategy, 000, 001, 002, 010, etc
  15. * Byte 2 and byte 3: Time to live. See TTL for definition
  16. * Byte 4 and byte 5: The number of times the volume has been compacted.
  17. * Rest bytes: Reserved
  18. */
  19. type SuperBlock struct {
  20. version Version
  21. ReplicaPlacement *ReplicaPlacement
  22. Ttl *TTL
  23. CompactRevision uint16
  24. }
  25. func (s *SuperBlock) Version() Version {
  26. return s.version
  27. }
  28. func (s *SuperBlock) Bytes() []byte {
  29. header := make([]byte, SuperBlockSize)
  30. header[0] = byte(s.version)
  31. header[1] = s.ReplicaPlacement.Byte()
  32. s.Ttl.ToBytes(header[2:4])
  33. util.Uint16toBytes(header[4:6], s.CompactRevision)
  34. return header
  35. }
  36. func (v *Volume) maybeWriteSuperBlock() error {
  37. stat, e := v.dataFile.Stat()
  38. if e != nil {
  39. glog.V(0).Infof("failed to stat datafile %s: %v", v.dataFile.Name(), e)
  40. return e
  41. }
  42. if stat.Size() == 0 {
  43. v.SuperBlock.version = CurrentVersion
  44. _, e = v.dataFile.Write(v.SuperBlock.Bytes())
  45. if e != nil && os.IsPermission(e) {
  46. //read-only, but zero length - recreate it!
  47. if v.dataFile, e = os.Create(v.dataFile.Name()); e == nil {
  48. if _, e = v.dataFile.Write(v.SuperBlock.Bytes()); e == nil {
  49. v.readOnly = false
  50. }
  51. }
  52. }
  53. }
  54. return e
  55. }
  56. func (v *Volume) readSuperBlock() (err error) {
  57. if _, err = v.dataFile.Seek(0, 0); err != nil {
  58. return fmt.Errorf("cannot seek to the beginning of %s: %v", v.dataFile.Name(), err)
  59. }
  60. header := make([]byte, SuperBlockSize)
  61. if _, e := v.dataFile.Read(header); e != nil {
  62. return fmt.Errorf("cannot read volume %d super block: %v", v.Id, e)
  63. }
  64. v.SuperBlock, err = ParseSuperBlock(header)
  65. return err
  66. }
  67. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  68. superBlock.version = Version(header[0])
  69. if superBlock.ReplicaPlacement, err = NewReplicaPlacementFromByte(header[1]); err != nil {
  70. err = fmt.Errorf("cannot read replica type: %s", err.Error())
  71. }
  72. superBlock.Ttl = LoadTTLFromBytes(header[2:4])
  73. superBlock.CompactRevision = util.BytesToUint16(header[4:6])
  74. return
  75. }