grpc_client.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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/master_pb"
  10. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  11. )
  12. func WithVolumeServerClient(volumeServer string, grpcDialOption grpc.DialOption, fn func(volume_server_pb.VolumeServerClient) error) error {
  13. grpcAddress, err := toVolumeServerGrpcAddress(volumeServer)
  14. if err != nil {
  15. return err
  16. }
  17. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  18. client := volume_server_pb.NewVolumeServerClient(grpcConnection)
  19. return fn(client)
  20. }, grpcAddress, grpcDialOption)
  21. }
  22. func toVolumeServerGrpcAddress(volumeServer string) (grpcAddress string, err error) {
  23. sepIndex := strings.LastIndex(volumeServer, ":")
  24. port, err := strconv.Atoi(volumeServer[sepIndex+1:])
  25. if err != nil {
  26. glog.Errorf("failed to parse volume server address: %v", volumeServer)
  27. return "", err
  28. }
  29. return fmt.Sprintf("%s:%d", volumeServer[0:sepIndex], port+10000), nil
  30. }
  31. func WithMasterServerClient(masterServer string, grpcDialOption grpc.DialOption, fn func(masterClient master_pb.SeaweedClient) error) error {
  32. masterGrpcAddress, parseErr := pb.ParseServerToGrpcAddress(masterServer)
  33. if parseErr != nil {
  34. return fmt.Errorf("failed to parse master grpc %v: %v", masterServer, parseErr)
  35. }
  36. return pb.WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  37. client := master_pb.NewSeaweedClient(grpcConnection)
  38. return fn(client)
  39. }, masterGrpcAddress, grpcDialOption)
  40. }