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.

84 lines
2.1 KiB

6 years ago
6 years ago
6 years ago
6 years ago
  1. package operation
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "sync"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  9. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. "google.golang.org/grpc"
  12. )
  13. var (
  14. grpcClients = make(map[string]*grpc.ClientConn)
  15. grpcClientsLock sync.Mutex
  16. )
  17. func WithVolumeServerClient(volumeServer string, fn func(volume_server_pb.VolumeServerClient) error) error {
  18. grpcAddress, err := toVolumeServerGrpcAddress(volumeServer)
  19. if err != nil {
  20. return err
  21. }
  22. grpcClientsLock.Lock()
  23. existingConnection, found := grpcClients[grpcAddress]
  24. if found {
  25. grpcClientsLock.Unlock()
  26. client := volume_server_pb.NewVolumeServerClient(existingConnection)
  27. return fn(client)
  28. }
  29. grpcConnection, err := util.GrpcDial(grpcAddress)
  30. if err != nil {
  31. grpcClientsLock.Unlock()
  32. return fmt.Errorf("fail to dial %s: %v", grpcAddress, err)
  33. }
  34. grpcClients[grpcAddress] = grpcConnection
  35. grpcClientsLock.Unlock()
  36. client := volume_server_pb.NewVolumeServerClient(grpcConnection)
  37. return fn(client)
  38. }
  39. func toVolumeServerGrpcAddress(volumeServer string) (grpcAddress string, err error) {
  40. sepIndex := strings.LastIndex(volumeServer, ":")
  41. port, err := strconv.Atoi(volumeServer[sepIndex+1:])
  42. if err != nil {
  43. glog.Errorf("failed to parse volume server address: %v", volumeServer)
  44. return "", err
  45. }
  46. return fmt.Sprintf("%s:%d", volumeServer[0:sepIndex], port+10000), nil
  47. }
  48. func withMasterServerClient(masterServer string, fn func(masterClient master_pb.SeaweedClient) error) error {
  49. grpcClientsLock.Lock()
  50. existingConnection, found := grpcClients[masterServer]
  51. if found {
  52. grpcClientsLock.Unlock()
  53. client := master_pb.NewSeaweedClient(existingConnection)
  54. return fn(client)
  55. }
  56. grpcConnection, err := util.GrpcDial(masterServer)
  57. if err != nil {
  58. grpcClientsLock.Unlock()
  59. return fmt.Errorf("fail to dial %s: %v", masterServer, err)
  60. }
  61. grpcClients[masterServer] = grpcConnection
  62. grpcClientsLock.Unlock()
  63. client := master_pb.NewSeaweedClient(grpcConnection)
  64. return fn(client)
  65. }