grpc_client_server.go 7.6 KB

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