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.

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