You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

246 lines
6.9 KiB

5 years ago
6 years ago
4 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
3 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  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. grpcConnection, err := GrpcDial(context.Background(), 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. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  100. vgc, err := getOrCreateConnection(address, opts...)
  101. if err != nil {
  102. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  103. }
  104. executionErr := fn(vgc.ClientConn)
  105. if executionErr != nil {
  106. if strings.Contains(executionErr.Error(), "transport") ||
  107. strings.Contains(executionErr.Error(), "connection closed") {
  108. grpcClientsLock.Lock()
  109. if t, ok := grpcClients[address]; ok {
  110. if t.version == vgc.version {
  111. vgc.Close()
  112. delete(grpcClients, address)
  113. }
  114. }
  115. grpcClientsLock.Unlock()
  116. }
  117. }
  118. return executionErr
  119. }
  120. func ParseServerAddress(server string, deltaPort int) (newServerAddress string, err error) {
  121. host, port, parseErr := hostAndPort(server)
  122. if parseErr != nil {
  123. return "", fmt.Errorf("server port parse error: %v", parseErr)
  124. }
  125. newPort := int(port) + deltaPort
  126. return util.JoinHostPort(host, newPort), nil
  127. }
  128. func hostAndPort(address string) (host string, port uint64, err error) {
  129. colonIndex := strings.LastIndex(address, ":")
  130. if colonIndex < 0 {
  131. return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
  132. }
  133. port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
  134. if err != nil {
  135. return "", 0, fmt.Errorf("server port parse error: %v", err)
  136. }
  137. return address[:colonIndex], port, err
  138. }
  139. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  140. host, port, parseErr := hostAndPort(server)
  141. if parseErr != nil {
  142. glog.Fatalf("server address %s parse error: %v", server, parseErr)
  143. }
  144. grpcPort := int(port) + 10000
  145. return util.JoinHostPort(host, grpcPort)
  146. }
  147. func GrpcAddressToServerAddress(grpcAddress string) (serverAddress string) {
  148. host, grpcPort, parseErr := hostAndPort(grpcAddress)
  149. if parseErr != nil {
  150. glog.Fatalf("server grpc address %s parse error: %v", grpcAddress, parseErr)
  151. }
  152. port := int(grpcPort) - 10000
  153. return util.JoinHostPort(host, port)
  154. }
  155. func WithMasterClient(master ServerAddress, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  156. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  157. client := master_pb.NewSeaweedClient(grpcConnection)
  158. return fn(client)
  159. }, master.ToGrpcAddress(), grpcDialOption)
  160. }
  161. func WithOneOfGrpcMasterClients(masterGrpcAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) (err error) {
  162. for _, masterGrpcAddress := range masterGrpcAddresses {
  163. err = WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  164. client := master_pb.NewSeaweedClient(grpcConnection)
  165. return fn(client)
  166. }, masterGrpcAddress.ToGrpcAddress(), grpcDialOption)
  167. if err == nil {
  168. return nil
  169. }
  170. }
  171. return err
  172. }
  173. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  174. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  175. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  176. return fn(client)
  177. }, brokerGrpcAddress, grpcDialOption)
  178. }
  179. func WithFilerClient(filer ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  180. return WithGrpcFilerClient(filer, grpcDialOption, fn)
  181. }
  182. func WithGrpcFilerClient(filerGrpcAddress ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  183. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  184. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  185. return fn(client)
  186. }, filerGrpcAddress.ToGrpcAddress(), grpcDialOption)
  187. }
  188. func WithOneOfGrpcFilerClients(filerAddresses []ServerAddress, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) (err error) {
  189. for _, filerAddress := range filerAddresses {
  190. err = WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  191. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  192. return fn(client)
  193. }, filerAddress.ToGrpcAddress(), grpcDialOption)
  194. if err == nil {
  195. return nil
  196. }
  197. }
  198. return err
  199. }