grpc_client_server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. package pb
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/keepalive"
  12. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  14. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  15. )
  16. const (
  17. Max_Message_Size = 1 << 30 // 1 GB
  18. )
  19. var (
  20. // cache grpc connections
  21. grpcClients = make(map[string]*grpc.ClientConn)
  22. grpcClientsLock sync.Mutex
  23. )
  24. func init() {
  25. http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
  26. }
  27. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  28. var options []grpc.ServerOption
  29. options = append(options,
  30. grpc.KeepaliveParams(keepalive.ServerParameters{
  31. Time: 10 * time.Second, // wait time before ping if no activity
  32. Timeout: 20 * time.Second, // ping timeout
  33. }),
  34. grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  35. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  36. PermitWithoutStream: false,
  37. }),
  38. grpc.MaxRecvMsgSize(Max_Message_Size),
  39. grpc.MaxSendMsgSize(Max_Message_Size),
  40. )
  41. for _, opt := range opts {
  42. if opt != nil {
  43. options = append(options, opt)
  44. }
  45. }
  46. return grpc.NewServer(options...)
  47. }
  48. func GrpcDial(ctx context.Context, address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  49. // opts = append(opts, grpc.WithBlock())
  50. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  51. var options []grpc.DialOption
  52. options = append(options,
  53. // grpc.WithInsecure(),
  54. grpc.WithDefaultCallOptions(
  55. grpc.MaxCallSendMsgSize(Max_Message_Size),
  56. grpc.MaxCallRecvMsgSize(Max_Message_Size),
  57. ),
  58. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  59. Time: 30 * time.Second, // client ping server if no activity for this long
  60. Timeout: 20 * time.Second,
  61. PermitWithoutStream: false,
  62. }))
  63. for _, opt := range opts {
  64. if opt != nil {
  65. options = append(options, opt)
  66. }
  67. }
  68. return grpc.DialContext(ctx, address, options...)
  69. }
  70. func getOrCreateConnection(address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  71. grpcClientsLock.Lock()
  72. defer grpcClientsLock.Unlock()
  73. existingConnection, found := grpcClients[address]
  74. if found {
  75. return existingConnection, nil
  76. }
  77. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  78. if err != nil {
  79. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  80. }
  81. grpcClients[address] = grpcConnection
  82. return grpcConnection, nil
  83. }
  84. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  85. grpcConnection, err := getOrCreateConnection(address, opts...)
  86. if err != nil {
  87. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  88. }
  89. return fn(grpcConnection)
  90. }
  91. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  92. colonIndex := strings.LastIndex(server, ":")
  93. if colonIndex < 0 {
  94. return "", fmt.Errorf("server should have hostname:port format: %v", server)
  95. }
  96. port, parseErr := strconv.ParseUint(server[colonIndex+1:], 10, 64)
  97. if parseErr != nil {
  98. return "", fmt.Errorf("server port parse error: %v", parseErr)
  99. }
  100. grpcPort := int(port) + 10000
  101. return fmt.Sprintf("%s:%d", server[:colonIndex], grpcPort), nil
  102. }
  103. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  104. hostnameAndPort := strings.Split(server, ":")
  105. if len(hostnameAndPort) != 2 {
  106. return fmt.Sprintf("unexpected server address: %s", server)
  107. }
  108. port, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  109. if parseErr != nil {
  110. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  111. }
  112. grpcPort := int(port) + 10000
  113. return fmt.Sprintf("%s:%d", hostnameAndPort[0], grpcPort)
  114. }
  115. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  116. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  117. if parseErr != nil {
  118. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  119. }
  120. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  121. client := master_pb.NewSeaweedClient(grpcConnection)
  122. return fn(client)
  123. }, masterGrpcAddress, grpcDialOption)
  124. }
  125. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  126. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  127. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  128. return fn(client)
  129. }, brokerGrpcAddress, grpcDialOption)
  130. }
  131. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  132. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  133. if parseErr != nil {
  134. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  135. }
  136. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  137. }
  138. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  139. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  140. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  141. return fn(client)
  142. }, filerGrpcAddress, grpcDialOption)
  143. }
  144. func ParseFilerGrpcAddress(filer string) (filerGrpcAddress string, err error) {
  145. hostnameAndPort := strings.Split(filer, ":")
  146. if len(hostnameAndPort) != 2 {
  147. return "", fmt.Errorf("filer should have hostname:port format: %v", hostnameAndPort)
  148. }
  149. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  150. if parseErr != nil {
  151. return "", fmt.Errorf("filer port parse error: %v", parseErr)
  152. }
  153. filerGrpcPort := int(filerPort) + 10000
  154. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  155. }