grpc_client.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package operation
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "google.golang.org/grpc"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  11. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  12. )
  13. func WithVolumeServerClient(volumeServer string, grpcDialOption grpc.DialOption, fn func(volume_server_pb.VolumeServerClient) error) error {
  14. grpcAddress, err := toVolumeServerGrpcAddress(volumeServer)
  15. if err != nil {
  16. return fmt.Errorf("failed to parse volume server %v: %v", volumeServer, err)
  17. }
  18. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  19. client := volume_server_pb.NewVolumeServerClient(grpcConnection)
  20. return fn(client)
  21. }, grpcAddress, grpcDialOption)
  22. }
  23. func toVolumeServerGrpcAddress(volumeServer string) (grpcAddress string, err error) {
  24. sepIndex := strings.LastIndex(volumeServer, ":")
  25. port, err := strconv.Atoi(volumeServer[sepIndex+1:])
  26. if err != nil {
  27. glog.Errorf("failed to parse volume server address: %v", volumeServer)
  28. return "", err
  29. }
  30. return fmt.Sprintf("%s:%d", volumeServer[0:sepIndex], port+10000), nil
  31. }
  32. func WithMasterServerClient(masterServer string, grpcDialOption grpc.DialOption, fn func(masterClient master_pb.SeaweedClient) error) error {
  33. masterGrpcAddress, parseErr := pb.ParseServerToGrpcAddress(masterServer)
  34. if parseErr != nil {
  35. return fmt.Errorf("failed to parse master %v: %v", masterServer, parseErr)
  36. }
  37. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  38. client := master_pb.NewSeaweedClient(grpcConnection)
  39. return fn(client)
  40. }, masterGrpcAddress, grpcDialOption)
  41. }
  42. func WithFilerServerClient(filerServer string, grpcDialOption grpc.DialOption, fn func(masterClient filer_pb.SeaweedFilerClient) error) error {
  43. filerGrpcAddress, parseErr := pb.ParseServerToGrpcAddress(filerServer)
  44. if parseErr != nil {
  45. return fmt.Errorf("failed to parse filer %v: %v", filerGrpcAddress, parseErr)
  46. }
  47. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  48. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  49. return fn(client)
  50. }, filerGrpcAddress, grpcDialOption)
  51. }