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.

65 lines
1.6 KiB

  1. package storage
  2. import (
  3. "code.google.com/p/weed-fs/go/glog"
  4. "fmt"
  5. "os"
  6. )
  7. const (
  8. SuperBlockSize = 8
  9. )
  10. type SuperBlock struct {
  11. version Version
  12. ReplicaPlacement *ReplicaPlacement
  13. }
  14. func (s *SuperBlock) Version() Version {
  15. return s.version
  16. }
  17. func (s *SuperBlock) Bytes() []byte {
  18. header := make([]byte, SuperBlockSize)
  19. header[0] = byte(s.version)
  20. header[1] = s.ReplicaPlacement.Byte()
  21. return header
  22. }
  23. func (v *Volume) maybeWriteSuperBlock() error {
  24. stat, e := v.dataFile.Stat()
  25. if e != nil {
  26. glog.V(0).Infof("failed to stat datafile %s: %s", v.dataFile, e.Error())
  27. return e
  28. }
  29. if stat.Size() == 0 {
  30. v.SuperBlock.version = CurrentVersion
  31. _, e = v.dataFile.Write(v.SuperBlock.Bytes())
  32. if e != nil && os.IsPermission(e) {
  33. //read-only, but zero length - recreate it!
  34. if v.dataFile, e = os.Create(v.dataFile.Name()); e == nil {
  35. if _, e = v.dataFile.Write(v.SuperBlock.Bytes()); e == nil {
  36. v.readOnly = false
  37. }
  38. }
  39. }
  40. }
  41. return e
  42. }
  43. func (v *Volume) readSuperBlock() (err error) {
  44. if _, err = v.dataFile.Seek(0, 0); err != nil {
  45. return fmt.Errorf("cannot seek to the beginning of %s: %s", v.dataFile.Name(), err.Error())
  46. }
  47. header := make([]byte, SuperBlockSize)
  48. if _, e := v.dataFile.Read(header); e != nil {
  49. return fmt.Errorf("cannot read superblock: %s", e.Error())
  50. }
  51. v.SuperBlock, err = ParseSuperBlock(header)
  52. return err
  53. }
  54. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  55. superBlock.version = Version(header[0])
  56. if superBlock.ReplicaPlacement, err = NewReplicaPlacementFromByte(header[1]); err != nil {
  57. err = fmt.Errorf("cannot read replica type: %s", err.Error())
  58. }
  59. return
  60. }