volume_info.go 2.2 KB

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