grpc_client_server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. grpc.WaitForReady(true),
  58. ),
  59. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  60. Time: 30 * time.Second, // client ping server if no activity for this long
  61. Timeout: 20 * time.Second,
  62. PermitWithoutStream: false,
  63. }))
  64. for _, opt := range opts {
  65. if opt != nil {
  66. options = append(options, opt)
  67. }
  68. }
  69. return grpc.DialContext(ctx, address, options...)
  70. }
  71. func getOrCreateConnection(address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  72. grpcClientsLock.Lock()
  73. defer grpcClientsLock.Unlock()
  74. existingConnection, found := grpcClients[address]
  75. if found {
  76. return existingConnection, nil
  77. }
  78. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  79. if err != nil {
  80. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  81. }
  82. grpcClients[address] = grpcConnection
  83. return grpcConnection, nil
  84. }
  85. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  86. grpcConnection, err := getOrCreateConnection(address, opts...)
  87. if err != nil {
  88. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  89. }
  90. return fn(grpcConnection)
  91. }
  92. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  93. colonIndex := strings.LastIndex(server, ":")
  94. if colonIndex < 0 {
  95. return "", fmt.Errorf("server should have hostname:port format: %v", server)
  96. }
  97. port, parseErr := strconv.ParseUint(server[colonIndex+1:], 10, 64)
  98. if parseErr != nil {
  99. return "", fmt.Errorf("server port parse error: %v", parseErr)
  100. }
  101. grpcPort := int(port) + 10000
  102. return fmt.Sprintf("%s:%d", server[:colonIndex], grpcPort), nil
  103. }
  104. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  105. hostnameAndPort := strings.Split(server, ":")
  106. if len(hostnameAndPort) != 2 {
  107. return fmt.Sprintf("unexpected server address: %s", server)
  108. }
  109. port, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  110. if parseErr != nil {
  111. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  112. }
  113. grpcPort := int(port) + 10000
  114. return fmt.Sprintf("%s:%d", hostnameAndPort[0], grpcPort)
  115. }
  116. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  117. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  118. if parseErr != nil {
  119. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  120. }
  121. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  122. client := master_pb.NewSeaweedClient(grpcConnection)
  123. return fn(client)
  124. }, masterGrpcAddress, grpcDialOption)
  125. }
  126. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  127. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  128. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  129. return fn(client)
  130. }, brokerGrpcAddress, grpcDialOption)
  131. }
  132. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  133. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  134. if parseErr != nil {
  135. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  136. }
  137. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  138. }
  139. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  140. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  141. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  142. return fn(client)
  143. }, filerGrpcAddress, grpcDialOption)
  144. }
  145. func ParseFilerGrpcAddress(filer string) (filerGrpcAddress string, err error) {
  146. hostnameAndPort := strings.Split(filer, ":")
  147. if len(hostnameAndPort) != 2 {
  148. return "", fmt.Errorf("filer should have hostname:port format: %v", hostnameAndPort)
  149. }
  150. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  151. if parseErr != nil {
  152. return "", fmt.Errorf("filer port parse error: %v", parseErr)
  153. }
  154. filerGrpcPort := int(filerPort) + 10000
  155. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  156. }