grpc_client_server.go 8.6 KB

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