grpc_client_server.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package pb
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/glog"
  6. "github.com/chrislusf/seaweedfs/weed/util"
  7. "math/rand"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "google.golang.org/grpc"
  14. "google.golang.org/grpc/keepalive"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  17. "github.com/chrislusf/seaweedfs/weed/pb/messaging_pb"
  18. )
  19. const (
  20. Max_Message_Size = 1 << 30 // 1 GB
  21. )
  22. var (
  23. // cache grpc connections
  24. grpcClients = make(map[string]*versionedGrpcClient)
  25. grpcClientsLock sync.Mutex
  26. )
  27. type versionedGrpcClient struct {
  28. *grpc.ClientConn
  29. version int
  30. errCount int
  31. }
  32. func init() {
  33. http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 1024
  34. http.DefaultTransport.(*http.Transport).MaxIdleConns = 1024
  35. }
  36. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  37. var options []grpc.ServerOption
  38. options = append(options,
  39. grpc.KeepaliveParams(keepalive.ServerParameters{
  40. Time: 10 * time.Second, // wait time before ping if no activity
  41. Timeout: 20 * time.Second, // ping timeout
  42. }),
  43. grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  44. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  45. PermitWithoutStream: true,
  46. }),
  47. grpc.MaxRecvMsgSize(Max_Message_Size),
  48. grpc.MaxSendMsgSize(Max_Message_Size),
  49. )
  50. for _, opt := range opts {
  51. if opt != nil {
  52. options = append(options, opt)
  53. }
  54. }
  55. return grpc.NewServer(options...)
  56. }
  57. func GrpcDial(ctx context.Context, address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  58. // opts = append(opts, grpc.WithBlock())
  59. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  60. var options []grpc.DialOption
  61. options = append(options,
  62. // grpc.WithInsecure(),
  63. grpc.WithDefaultCallOptions(
  64. grpc.MaxCallSendMsgSize(Max_Message_Size),
  65. grpc.MaxCallRecvMsgSize(Max_Message_Size),
  66. ),
  67. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  68. Time: 30 * time.Second, // client ping server if no activity for this long
  69. Timeout: 20 * time.Second,
  70. PermitWithoutStream: true,
  71. }))
  72. for _, opt := range opts {
  73. if opt != nil {
  74. options = append(options, opt)
  75. }
  76. }
  77. return grpc.DialContext(ctx, address, options...)
  78. }
  79. func getOrCreateConnection(address string, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
  80. grpcClientsLock.Lock()
  81. defer grpcClientsLock.Unlock()
  82. existingConnection, found := grpcClients[address]
  83. if found {
  84. return existingConnection, nil
  85. }
  86. ctx := context.Background()
  87. grpcConnection, err := GrpcDial(ctx, address, opts...)
  88. if err != nil {
  89. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  90. }
  91. vgc := &versionedGrpcClient{
  92. grpcConnection,
  93. rand.Int(),
  94. 0,
  95. }
  96. grpcClients[address] = vgc
  97. return vgc, nil
  98. }
  99. // WithGrpcClient In streamingMode, always use a fresh connection. Otherwise, try to reuse an existing connection.
  100. func WithGrpcClient(streamingMode bool, fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  101. if !streamingMode {
  102. vgc, err := getOrCreateConnection(address, opts...)
  103. if err != nil {
  104. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  105. }
  106. executionErr := fn(vgc.ClientConn)
  107. if executionErr != nil {
  108. if strings.Contains(executionErr.Error(), "transport") ||
  109. strings.Contains(executionErr.Error(), "connection closed") {
  110. grpcClientsLock.Lock()
  111. if t, ok := grpcClients[address]; ok {
  112. if t.version == vgc.version {
  113. vgc.Close()
  114. delete(grpcClients, address)
  115. }
  116. }
  117. grpcClientsLock.Unlock()
  118. }
  119. }
  120. return executionErr
  121. } else {
  122. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  123. if err != nil {
  124. return fmt.Errorf("fail to dial %s: %v", address, err)
  125. }
  126. defer grpcConnection.Close()
  127. executionErr := fn(grpcConnection)
  128. if executionErr != nil {
  129. return executionErr
  130. }
  131. return nil
  132. }
  133. }
  134. func ParseServerAddress(server string, deltaPort int) (newServerAddress string, err error) {
  135. host, port, parseErr := hostAndPort(server)
  136. if parseErr != nil {
  137. return "", fmt.Errorf("server port parse error: %v", parseErr)
  138. }
  139. newPort := int(port) + deltaPort
  140. return util.JoinHostPort(host, newPort), nil
  141. }
  142. func hostAndPort(address string) (host string, port uint64, err error) {
  143. colonIndex := strings.LastIndex(address, ":")
  144. if colonIndex < 0 {
  145. return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
  146. }
  147. port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
  148. if err != nil {
  149. return "", 0, fmt.Errorf("server port parse error: %v", err)
  150. }
  151. return address[:colonIndex], port, err
  152. }
  153. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  154. host, port, parseErr := hostAndPort(server)
  155. if parseErr != nil {
  156. glog.Fatalf("server address %s parse error: %v", server, parseErr)
  157. }
  158. grpcPort := int(port) + 10000
  159. return util.JoinHostPort(host, grpcPort)
  160. }
  161. func GrpcAddressToServerAddress(grpcAddress string) (serverAddress string) {
  162. host, grpcPort, parseErr := hostAndPort(grpcAddress)
  163. if parseErr != nil {
  164. glog.Fatalf("server grpc address %s parse error: %v", grpcAddress, parseErr)
  165. }
  166. port := int(grpcPort) - 10000
  167. return util.JoinHostPort(host, port)
  168. }
  169. func WithMasterClient(streamingMode bool, master ServerAddress, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  170. return WithGrpcClient(streamingMode, func(grpcConnection *grpc.ClientConn) error {
  171. client := master_pb.NewSeaweedClient(grpcConnection)
  172. return fn(client)
  173. }, master.ToGrpcAddress(), grpcDialOption)
  174. }
  175. func WithOneOfGrpcMasterClients(streamingMode bool, masterGrpcAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) (err error) {
  176. for _, masterGrpcAddress := range masterGrpcAddresses {
  177. err = WithGrpcClient(streamingMode, func(grpcConnection *grpc.ClientConn) error {
  178. client := master_pb.NewSeaweedClient(grpcConnection)
  179. return fn(client)
  180. }, masterGrpcAddress.ToGrpcAddress(), grpcDialOption)
  181. if err == nil {
  182. return nil
  183. }
  184. }
  185. return err
  186. }
  187. func WithBrokerGrpcClient(streamingMode bool, brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  188. return WithGrpcClient(streamingMode, func(grpcConnection *grpc.ClientConn) error {
  189. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  190. return fn(client)
  191. }, brokerGrpcAddress, grpcDialOption)
  192. }
  193. func WithFilerClient(streamingMode bool, filer ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  194. return WithGrpcFilerClient(streamingMode, filer, grpcDialOption, fn)
  195. }
  196. func WithGrpcFilerClient(streamingMode bool, filerGrpcAddress ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  197. return WithGrpcClient(streamingMode, func(grpcConnection *grpc.ClientConn) error {
  198. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  199. return fn(client)
  200. }, filerGrpcAddress.ToGrpcAddress(), grpcDialOption)
  201. }
  202. func WithOneOfGrpcFilerClients(streamingMode bool, filerAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) (err error) {
  203. for _, filerAddress := range filerAddresses {
  204. err = WithGrpcClient(streamingMode, func(grpcConnection *grpc.ClientConn) error {
  205. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  206. return fn(client)
  207. }, filerAddress.ToGrpcAddress(), grpcDialOption)
  208. if err == nil {
  209. return nil
  210. }
  211. }
  212. return err
  213. }