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.

94 lines
2.2 KiB

6 years ago
6 years ago
  1. package source
  2. import (
  3. "io"
  4. "github.com/chrislusf/seaweedfs/weed/util"
  5. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  6. "fmt"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "strings"
  9. "context"
  10. )
  11. type ReplicationSource interface {
  12. ReadPart(part string) io.ReadCloser
  13. }
  14. type FilerSource struct {
  15. grpcAddress string
  16. Dir string
  17. }
  18. func (fs *FilerSource) Initialize(configuration util.Configuration) error {
  19. return fs.initialize(
  20. configuration.GetString("grpcAddress"),
  21. configuration.GetString("directory"),
  22. )
  23. }
  24. func (fs *FilerSource) initialize(grpcAddress string, dir string) (err error) {
  25. fs.grpcAddress = grpcAddress
  26. fs.Dir = dir
  27. return nil
  28. }
  29. func (fs *FilerSource) ReadPart(part string) (readCloser io.ReadCloser, err error) {
  30. vid2Locations := make(map[string]*filer_pb.Locations)
  31. vid := volumeId(part)
  32. err = fs.withFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  33. glog.V(4).Infof("read lookup volume id locations: %v", vid)
  34. resp, err := client.LookupVolume(context.Background(), &filer_pb.LookupVolumeRequest{
  35. VolumeIds: []string{vid},
  36. })
  37. if err != nil {
  38. return err
  39. }
  40. vid2Locations = resp.LocationsMap
  41. return nil
  42. })
  43. if err != nil {
  44. glog.V(1).Infof("replication lookup volume id %s: %v", vid, err)
  45. return nil, fmt.Errorf("replication lookup volume id %s: %v", vid, err)
  46. }
  47. locations := vid2Locations[vid]
  48. if locations == nil || len(locations.Locations) == 0 {
  49. glog.V(1).Infof("replication locate volume id %s: %v", vid, err)
  50. return nil, fmt.Errorf("replication locate volume id %s: %v", vid, err)
  51. }
  52. fileUrl := fmt.Sprintf("http://%s/%s", locations.Locations[0].Url, part)
  53. _, readCloser, err = util.DownloadUrl(fileUrl)
  54. return readCloser, err
  55. }
  56. func (fs *FilerSource) withFilerClient(fn func(filer_pb.SeaweedFilerClient) error) error {
  57. grpcConnection, err := util.GrpcDial(fs.grpcAddress)
  58. if err != nil {
  59. return fmt.Errorf("fail to dial %s: %v", fs.grpcAddress, err)
  60. }
  61. defer grpcConnection.Close()
  62. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  63. return fn(client)
  64. }
  65. func volumeId(fileId string) string {
  66. lastCommaIndex := strings.LastIndex(fileId, ",")
  67. if lastCommaIndex > 0 {
  68. return fileId[:lastCommaIndex]
  69. }
  70. return fileId
  71. }