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.

82 lines
2.2 KiB

  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, 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. v.dataFileSize = SuperBlockSize
  54. }
  55. return e
  56. }
  57. func (v *Volume) readSuperBlock() (err error) {
  58. if _, err = v.dataFile.Seek(0, 0); err != nil {
  59. return fmt.Errorf("cannot seek to the beginning of %s: %v", v.dataFile.Name(), err)
  60. }
  61. header := make([]byte, SuperBlockSize)
  62. if _, e := v.dataFile.Read(header); e != nil {
  63. return fmt.Errorf("cannot read volume %d super block: %v", v.Id, e)
  64. }
  65. v.SuperBlock, err = ParseSuperBlock(header)
  66. return err
  67. }
  68. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  69. superBlock.version = Version(header[0])
  70. if superBlock.ReplicaPlacement, err = NewReplicaPlacementFromByte(header[1]); err != nil {
  71. err = fmt.Errorf("cannot read replica type: %s", err.Error())
  72. }
  73. superBlock.Ttl = LoadTTLFromBytes(header[2:4])
  74. superBlock.CompactRevision = util.BytesToUint16(header[4:6])
  75. return
  76. }