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.

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