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.

216 lines
6.4 KiB

5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 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
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
  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. http.DefaultTransport.(*http.Transport).MaxIdleConns = 1024
  27. }
  28. func NewGrpcServer(opts ...grpc.ServerOption) *grpc.Server {
  29. var options []grpc.ServerOption
  30. options = append(options,
  31. grpc.KeepaliveParams(keepalive.ServerParameters{
  32. Time: 10 * time.Second, // wait time before ping if no activity
  33. Timeout: 20 * time.Second, // ping timeout
  34. MaxConnectionAge: 10 * time.Hour,
  35. }),
  36. grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
  37. MinTime: 60 * time.Second, // min time a client should wait before sending a ping
  38. PermitWithoutStream: false,
  39. }),
  40. grpc.MaxRecvMsgSize(Max_Message_Size),
  41. grpc.MaxSendMsgSize(Max_Message_Size),
  42. )
  43. for _, opt := range opts {
  44. if opt != nil {
  45. options = append(options, opt)
  46. }
  47. }
  48. return grpc.NewServer(options...)
  49. }
  50. func GrpcDial(ctx context.Context, address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  51. // opts = append(opts, grpc.WithBlock())
  52. // opts = append(opts, grpc.WithTimeout(time.Duration(5*time.Second)))
  53. var options []grpc.DialOption
  54. options = append(options,
  55. // grpc.WithInsecure(),
  56. grpc.WithDefaultCallOptions(
  57. grpc.MaxCallSendMsgSize(Max_Message_Size),
  58. grpc.MaxCallRecvMsgSize(Max_Message_Size),
  59. grpc.WaitForReady(true),
  60. ),
  61. grpc.WithKeepaliveParams(keepalive.ClientParameters{
  62. Time: 30 * time.Second, // client ping server if no activity for this long
  63. Timeout: 20 * time.Second,
  64. PermitWithoutStream: false,
  65. }))
  66. for _, opt := range opts {
  67. if opt != nil {
  68. options = append(options, opt)
  69. }
  70. }
  71. return grpc.DialContext(ctx, address, options...)
  72. }
  73. func getOrCreateConnection(address string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
  74. grpcClientsLock.Lock()
  75. defer grpcClientsLock.Unlock()
  76. existingConnection, found := grpcClients[address]
  77. if found {
  78. return existingConnection, nil
  79. }
  80. grpcConnection, err := GrpcDial(context.Background(), address, opts...)
  81. if err != nil {
  82. return nil, fmt.Errorf("fail to dial %s: %v", address, err)
  83. }
  84. grpcClients[address] = grpcConnection
  85. return grpcConnection, nil
  86. }
  87. func WithCachedGrpcClient(fn func(*grpc.ClientConn) error, address string, opts ...grpc.DialOption) error {
  88. grpcConnection, err := getOrCreateConnection(address, opts...)
  89. if err != nil {
  90. return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
  91. }
  92. return fn(grpcConnection)
  93. }
  94. func ParseServerToGrpcAddress(server string) (serverGrpcAddress string, err error) {
  95. colonIndex := strings.LastIndex(server, ":")
  96. if colonIndex < 0 {
  97. return "", fmt.Errorf("server should have hostname:port format: %v", server)
  98. }
  99. port, parseErr := strconv.ParseUint(server[colonIndex+1:], 10, 64)
  100. if parseErr != nil {
  101. return "", fmt.Errorf("server port parse error: %v", parseErr)
  102. }
  103. grpcPort := int(port) + 10000
  104. return fmt.Sprintf("%s:%d", server[:colonIndex], grpcPort), nil
  105. }
  106. func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
  107. hostnameAndPort := strings.Split(server, ":")
  108. if len(hostnameAndPort) != 2 {
  109. return fmt.Sprintf("unexpected server address: %s", server)
  110. }
  111. port, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  112. if parseErr != nil {
  113. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  114. }
  115. grpcPort := int(port) + 10000
  116. return fmt.Sprintf("%s:%d", hostnameAndPort[0], grpcPort)
  117. }
  118. func GrpcAddressToServerAddress(grpcAddress string) (serverAddress string) {
  119. hostnameAndPort := strings.Split(grpcAddress, ":")
  120. if len(hostnameAndPort) != 2 {
  121. return fmt.Sprintf("unexpected grpcAddress: %s", grpcAddress)
  122. }
  123. grpcPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  124. if parseErr != nil {
  125. return fmt.Sprintf("failed to parse port for %s:%s", hostnameAndPort[0], hostnameAndPort[1])
  126. }
  127. port := int(grpcPort) - 10000
  128. return fmt.Sprintf("%s:%d", hostnameAndPort[0], port)
  129. }
  130. func WithMasterClient(master string, grpcDialOption grpc.DialOption, fn func(client master_pb.SeaweedClient) error) error {
  131. masterGrpcAddress, parseErr := ParseServerToGrpcAddress(master)
  132. if parseErr != nil {
  133. return fmt.Errorf("failed to parse master grpc %v: %v", master, parseErr)
  134. }
  135. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  136. client := master_pb.NewSeaweedClient(grpcConnection)
  137. return fn(client)
  138. }, masterGrpcAddress, grpcDialOption)
  139. }
  140. func WithBrokerGrpcClient(brokerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client messaging_pb.SeaweedMessagingClient) error) error {
  141. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  142. client := messaging_pb.NewSeaweedMessagingClient(grpcConnection)
  143. return fn(client)
  144. }, brokerGrpcAddress, grpcDialOption)
  145. }
  146. func WithFilerClient(filer string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  147. filerGrpcAddress, parseErr := ParseServerToGrpcAddress(filer)
  148. if parseErr != nil {
  149. return fmt.Errorf("failed to parse filer grpc %v: %v", filer, parseErr)
  150. }
  151. return WithGrpcFilerClient(filerGrpcAddress, grpcDialOption, fn)
  152. }
  153. func WithGrpcFilerClient(filerGrpcAddress string, grpcDialOption grpc.DialOption, fn func(client filer_pb.SeaweedFilerClient) error) error {
  154. return WithCachedGrpcClient(func(grpcConnection *grpc.ClientConn) error {
  155. client := filer_pb.NewSeaweedFilerClient(grpcConnection)
  156. return fn(client)
  157. }, filerGrpcAddress, grpcDialOption)
  158. }
  159. func ParseFilerGrpcAddress(filer string) (filerGrpcAddress string, err error) {
  160. hostnameAndPort := strings.Split(filer, ":")
  161. if len(hostnameAndPort) != 2 {
  162. return "", fmt.Errorf("filer should have hostname:port format: %v", hostnameAndPort)
  163. }
  164. filerPort, parseErr := strconv.ParseUint(hostnameAndPort[1], 10, 64)
  165. if parseErr != nil {
  166. return "", fmt.Errorf("filer port parse error: %v", parseErr)
  167. }
  168. filerGrpcPort := int(filerPort) + 10000
  169. return fmt.Sprintf("%s:%d", hostnameAndPort[0], filerGrpcPort), nil
  170. }