volume_info.go 2.1 KB

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