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.

76 lines
2.0 KiB

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