volume_info.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package pb
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. _ "github.com/chrislusf/seaweedfs/weed/storage/backend/s3_backend"
  7. "github.com/chrislusf/seaweedfs/weed/util"
  8. "github.com/golang/protobuf/jsonpb"
  9. "github.com/chrislusf/seaweedfs/weed/util/log"
  10. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  11. )
  12. // MaybeLoadVolumeInfo load the file data as *volume_server_pb.VolumeInfo, the returned volumeInfo will not be nil
  13. func MaybeLoadVolumeInfo(fileName string) (*volume_server_pb.VolumeInfo, bool, error) {
  14. volumeInfo := &volume_server_pb.VolumeInfo{}
  15. log.Debugf("maybeLoadVolumeInfo checks %s", fileName)
  16. if exists, canRead, _, _, _ := util.CheckFile(fileName); !exists || !canRead {
  17. if !exists {
  18. return volumeInfo, false, nil
  19. }
  20. if !canRead {
  21. log.Warnf("can not read %s", fileName)
  22. return volumeInfo, false, fmt.Errorf("can not read %s", fileName)
  23. }
  24. return volumeInfo, false, nil
  25. }
  26. log.Debugf("maybeLoadVolumeInfo reads %s", fileName)
  27. tierData, readErr := ioutil.ReadFile(fileName)
  28. if readErr != nil {
  29. log.Warnf("fail to read %s : %v", fileName, readErr)
  30. return volumeInfo, false, fmt.Errorf("fail to read %s : %v", fileName, readErr)
  31. }
  32. log.Debugf("maybeLoadVolumeInfo Unmarshal volume info %v", fileName)
  33. if err := jsonpb.Unmarshal(bytes.NewReader(tierData), volumeInfo); err != nil {
  34. log.Warnf("unmarshal error: %v", err)
  35. return volumeInfo, false, fmt.Errorf("unmarshal error: %v", err)
  36. }
  37. if len(volumeInfo.GetFiles()) == 0 {
  38. return volumeInfo, false, nil
  39. }
  40. return volumeInfo, true, nil
  41. }
  42. func SaveVolumeInfo(fileName string, volumeInfo *volume_server_pb.VolumeInfo) error {
  43. if exists, _, canWrite, _, _ := util.CheckFile(fileName); exists && !canWrite {
  44. return fmt.Errorf("%s not writable", fileName)
  45. }
  46. m := jsonpb.Marshaler{
  47. EmitDefaults: true,
  48. Indent: " ",
  49. }
  50. text, marshalErr := m.MarshalToString(volumeInfo)
  51. if marshalErr != nil {
  52. return fmt.Errorf("marshal to %s: %v", fileName, marshalErr)
  53. }
  54. writeErr := ioutil.WriteFile(fileName, []byte(text), 0755)
  55. if writeErr != nil {
  56. return fmt.Errorf("fail to write %s : %v", fileName, writeErr)
  57. }
  58. return nil
  59. }