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.

75 lines
1.9 KiB

  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/glog"
  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) {
  14. volumeInfo := &volume_server_pb.VolumeInfo{}
  15. glog.V(1).Infof("maybeLoadVolumeInfo checks %s", fileName)
  16. if exists, canRead, _, _, _ := util.CheckFile(fileName); !exists || !canRead {
  17. if !exists {
  18. return volumeInfo, false
  19. }
  20. if !canRead {
  21. glog.Warningf("can not read %s", fileName)
  22. }
  23. return volumeInfo, false
  24. }
  25. glog.V(1).Infof("maybeLoadVolumeInfo reads %s", fileName)
  26. tierData, readErr := ioutil.ReadFile(fileName)
  27. if readErr != nil {
  28. glog.Warningf("fail to read %s : %v", fileName, readErr)
  29. return volumeInfo, false
  30. }
  31. glog.V(1).Infof("maybeLoadVolumeInfo Unmarshal volume info %v", fileName)
  32. if err := jsonpb.Unmarshal(bytes.NewReader(tierData), volumeInfo); err != nil {
  33. glog.Warningf("unmarshal error: %v", err)
  34. return volumeInfo, false
  35. }
  36. if len(volumeInfo.GetFiles()) == 0 {
  37. return volumeInfo, false
  38. }
  39. return volumeInfo, true
  40. }
  41. func SaveVolumeInfo(fileName string, volumeInfo *volume_server_pb.VolumeInfo) error {
  42. if exists, _, canWrite, _, _ := util.CheckFile(fileName); exists && !canWrite {
  43. return fmt.Errorf("%s not writable", fileName)
  44. }
  45. m := jsonpb.Marshaler{
  46. EmitDefaults: true,
  47. Indent: " ",
  48. }
  49. text, marshalErr := m.MarshalToString(volumeInfo)
  50. if marshalErr != nil {
  51. return fmt.Errorf("marshal to %s: %v", fileName, marshalErr)
  52. }
  53. writeErr := ioutil.WriteFile(fileName, []byte(text), 0755)
  54. if writeErr != nil {
  55. return fmt.Errorf("fail to write %s : %v", fileName, writeErr)
  56. }
  57. return nil
  58. }